Quick line:
#include <iostream>#include<string.h>#include<stdio.h>#include<cmath>using namespacestd;voidQ_sort (intA[],intLowintHigh ) { if(Low >= High)return; intFirst =Low ; intLast =High ; intKey =A[first]; while(First <Last ) { while(First < last && A[last] >=key) { Last--; } A[first]=A[last]; while(First < last && A[first] <=key) { First++; } A[last]=A[first]; } A[first]=key; Q_sort (A,low,last); Q_sort (A,last+1, high);}intn =9;intA[] = { $, the, -, the, the, -, the, -, -};voidprint () { for(intI=0; i<n;i++) {printf ("%d", A[i]); } printf ("\ n");}intMain () {print (); Q_sort (A,0,8); Print (); return 0;}
Quick row: In the array that is currently being sorted, select a number as the datum, then divide the array into two parts, part is smaller than the current number, the other part is larger than this datum, then divide the same operation recursively, the worst time complexity is the worst time O (N2), and the average time complexity is O (NLGN).
Merge sort:
#include <iostream>#include<string.h>#include<stdio.h>using namespacestd;#defineMAXN 1100intMMAP[MAXN];voidMerge (intNum[],intFirstintMidintLast ) { intI=First ; intj = mid+1; intIndex =0; while(I<=mid && J <=Last ) { if(Num[i] <=Num[j]) {Mmap[index+ +] = num[i++]; } Else{Mmap[index+ +] = num[j++]; } } while(i<=mid) {Mmap[index+ +] = num[i++]; } while(J <=Last ) {Mmap[index+ +] = num[j++]; } for(intm=0; m<index;m++) {Num[first++] =Mmap[m]; }}voidMergeSort (intNum[],intFirstintLast ) { if(First = =Last ) { return; } intMid = (first + last)/2; MergeSort (Num,first,mid); MergeSort (Num,mid+1, last); Merge (num,first,mid,last);}intNUM[MAXN];intMain () {intN; CIN>>N; for(intI=0; i<n;i++) {cin>>Num[i]; } mergesort (num,0, N-1); for(intI=0; i<n;i++) {printf ("%d", Num[i]); } printf ("\ n"); return 0;}
Merge sort: According to the thought of divide and conquer, want to divide data into two paragraphs, then recursively, then merge
The complexity of Time is: O (NLGN)
Bubble Sort:
#include <iostream>#include<string.h>#include<stdio.h>using namespacestd;#defineMAXN 1100intMMAP[MAXN];intN;voidBubble_sort () {inttemp; BOOLFlag; for(intI=0; i<n-1;i++) {flag=0; for(intj=n-2; j>=i;j--) { if(Mmap[j] > mmap[j+1]) {temp= mmap[j+1]; Mmap[j+1] =Mmap[j]; MMAP[J]=temp; Flag=1; } } if(!flag) Break; }}intMain () { while(~SCANF ("%d",&N)) { for(intI=0; i<n;i++) {scanf ("%d",&Mmap[i]); } bubble_sort (); for(intI=0; i<n;i++) {printf ("%d", Mmap[i]); } printf ("\ n"); } return 0;}
Bubble sort: Compares the two elements in the array, then finds the largest one to be put to the last, and then loops
The complexity of Time is: O (n2)
Sort-bubble, merge, quick line difference