The exchange sort, as the name implies, must be achieved by comparing and exchanging two numbers or several numbers to achieve a sort order. Exchange-based sorting mainly has bubble sort and quick sort .
1. Bubble sort
By comparing and swapping between 22, a maximum record (ascending) or a minimum record (descending) is emitted each time.
voidBubblesort (intArr[],intN) { intOuter,inner; for(outer=1; outer<=n;outer++){ for(inner=1; inner<=n-outer;inner++){ if(arr[inner+1]<Arr[inner]) {arr[0] =Arr[inner]; Arr[inner]= arr[inner+1]; Arr[inner+1] = arr[0]; } } }}
The above is a regular bubble sort, but if the last few records have not been exchanged, that is, the subsequent records are ordered, for the regular bubble sort, no matter how it will bubble, naturally increase the time of the sorting. Therefore, the above general bubble sorting can be improved. As follows: We use a exchangeindex to record the last position of each exchange.
voidBubblesortmodified (intArr[],intN) { intOuter,inner; intExchangeindex =N; intExchange; while(exchangeindex>1) {Exchange=1; for(inner=1; inner<=exchangeindex;inner++){ if(arr[inner+1]<Arr[inner]) {arr[0] =Arr[inner]; Arr[inner]= arr[inner+1]; Arr[inner+1] = arr[0]; Exchange=inner; }} Exchangeindex=Exchange; }}
2. Quick Sort
Quick sort: The whole sequence is divided into left and right groups based on a record in the sequence, the left sequence is less than the datum, and the second is greater than the datum. Then select a datum for the left and right sequence, and then go down to the left and last sequence record number is 0.
int_quicksort (intArr[],intBeginintend) {arr[0] =Arr[begin]; while(Begin <end) { while(Begin<end && arr[end]>arr[0]) End--; if(begin<end) Arr[begin]= Arr[end],arr[end] = arr[0],begin + +; Else returnbegin; while(Begin<end && arr[begin]<arr[0]) begin++; if(begin<end) Arr[end]= Arr[begin],arr[begin] = arr[0],end--; Else returnend; } }voidQuickSort (intArr[],intBeginintend) { intMiddle; if(Begin <end) {Middle=_quicksort (arr,begin,end); QuickSort (Arr,begin,middle-1); QuickSort (Arr,middle+1, end); }}
3. Summary
Bubble sort: Time complexity O (N2), is a stable sorting algorithm.
Quick sort: Time complexity O (nlog2n), is an unstable sorting algorithm, and the average performance of all sorting algorithms is the best.
However, if the ordered sequence is ordered or basically ordered, the performance of the fast sorting becomes very poor, it degrades into a bubble sort, and the time complexity is O (N2). So a quick sort is appropriate for those random sequences of sorts.
The exchange sort of the story of the data structure