Classic sort: bubble sort + Select sort
Example Fjutoj 1842
Bubble sort
The principle is to take the next two numbers to compare the size, determine whether the exchange.
In order from small to large for example, bubble sort like bubbles, the smallest number slowly floating up, the largest number of slowly sinking down. Then the last one is the largest number in the original sequence. Then only the 1~ (n-1) numbers are ordered, and the second-to-last number after completion is the largest value in the 1~n-1 element of the original sequence. So repeat, the n-1 times must be able to complete the sorting. Reference code:
1#include <stdio.h>2 voidBubblesort (int*,int);3 intMain ()4 {5 intA[] = {9,5,3,6,7,2,5,4,3,9}, I;6 ints =sizeof(a)/sizeof(int);7Puts"before sort:");8 for(i =0; I < S; i++)9printf"%d", A[i]);Ten Bubblesort (a,s); OnePuts"\nafter Sort:"); A for(i =0; I < S; i++) -printf"%d", A[i]); - return 0; the } - voidBubblesort (int*a,ints) - { - intI, J, TMP; + for(i =0; I < S1; i++) - { + for(j =1; J < S-i; J + +) A { at if(a[j-1] >A[j]) - { -TMP = a[j-1]; -a[j-1] =A[j]; -A[J] =tmp; - } in } - } to}
Then an optimization can be made if the whole trip down is not a single exchange, then determine that the sequence has been satisfied with the monotony, the direct jump out of the loop can save time. The code is as follows
1 voidBubblesort (int*a,ints)2 {3 intI, J, TMP;4 Charswap;5 for(i =0; I < S1; i++)6 {7Swap =0;8 for(j =1; J < S-i; J + +)9 {Ten if(a[j-1] >A[j]) One { ASwap =1; -TMP = a[j-1]; -a[j-1] =A[j]; theA[J] =tmp; - } - } - if(Swap = =0) Break; + } -}
Select sort
Take the small-to-large sort as an example. The principle is to pick a minimum value in the sequence and then swap with the first one in the sequence. So, the first one is the smallest number in the whole sequence. Then do this for the sequence starting with the second number, get the smallest number in the remaining sequence, swap with the second number in the original sequence, and so on, and do the n-1 to complete the sort. Reference code:
voidSelectsort (int*a,ints) { intI, J, TMP, Min_num_index; for(i =0; I < S1; i++) {Min_num_index=i; for(j = i+1; J < S; J + +) { if(A[j] <A[min_num_index]) Min_num_index=J; } if(Min_num_index! =i) {tmp=A[i]; A[i]=A[min_num_index]; A[min_num_index]=tmp; } }}
The above code and text are hand-punched, wrong also please correct me!
Classic sort: bubble sort + Select Sort Summary