[Wiki] Sort cơ bản 1 - Insert Sort - Sắp xếp chèn

GIF

#include <stdio.h>

int main()

{

int length = 5;

int array[] = {5,2,4,3,1};

for(int unsorted_id = 1; unsorted_id < length; unsorted_id++) {

int element = array[unsorted_id];

int sorted_id = unsorted_id - 1;

while(sorted_id >= 0 && element > array[sorted_id]) {

array[sorted_id+1] = array[sorted_id]; // shift

sorted_id--;

}

array[sorted_id+1] = element; // insert

}

//output

for(int i = 0; i < length; ++i)

printf("%d ", array[i]);

return 0;

}

daynhauhoc

http://daynhauhoc.com/
Follow
4.7 Star App Store Review!
Cpl.dev***uke
The Communities are great you rarely see anyone get in to an argument :)
king***ing
Love Love LOVE
Download

Select Collections