This implementation is the brute force method of two examples, the choice of sorting method and bubble sorting method, the use of the compilation environment is vs2013, the following two algorithms to do a brief introduction, and then the two algorithm of C + + implementation code.
The selection sort method compares the entire list, each time the scan ends to find the smallest element in the previous position, while the bubbling sort method compares the adjacent two elements, placing the larger elements behind, so that the current largest element is placed behind the list at the end of a scan.
The algorithm for two sorting methods is as follows:
Select Sort method Selectionsort (A[0....n-1]) Input: A sortable array a[0....n-1], Output: An array of ascending sort a[0....n-1] For I <-0 to N-2 do Min <-i; For J <-i+1 to N-1 do If A[J] < a[min] min <-j; Swap a[i] and a[min]; |
The input scale of the algorithm is the number of elements n, the basic operation is the IF statement comparison steps: A[j] < a[min], compared to the number of executions: (n-1) N/2, that is, θ (n2).
Bubble Sort algorithm:
Bubblesort (A[0....n-1]) Input: A sortable array a[0....n-1] Output: An array of ascending sort a[0....n-1] For I <-0 to N-2 do For J <-0 to N-2-i do If A[J+1]<A[J] Swap A[j+1]anda[j] |
The time complexity of the algorithm is the same as the time complexity of the selection sort is θ (n2).
#include <iostream>using namespacestd;voidSelectionsort (intIsort[],intn);voidBubblesort (intIsort[],intn);voidSwapint&a,int&b);
//-------------------main Function-------------------intMain () {inta[Ten]; for(inti =0; I <Ten; i++) {cin>>A[i]; } getchar (); //Selectionsort (A, 10); //The argument passed here is the array name,//That is , the address is passed so that the called function can change the value of array A. Bubblesort (A,Ten); for(inti =0; I <Ten; i++) {cout<<" "<<A[i]; } getchar (); return 1;}//-------------------Select the sorting method-------------------voidSelectionsort (intIsort[],intN) { inti =0, j =0, min=0; for(i =0; I < n-1; i++) {min=i; for(j = i +1; J < N; J + +){ if(Isort[j]<isort[min]) {//If you want to get a descending order, just change the judging condition here to if (Isort[j]>isort[min]).Min =J; }} swap (Isort[i], isort[min]); }}//-------------------Bubble Sorting Method-------------------voidBubblesort (intIsort[],intN) { inti =0, j =0; for(i =0; I < n-1; i++){ for(j =0; J < N-1I J + +){ if(Isort[j +1] <Isort[j]) {Swap (Isort[j+1], isort[j]); } } }}//-------------------Interchange Element-------------------voidSwapint&a,int&b) { inttemp; Temp=A; A=b; b=temp;}
Algorithm--The choice of brute force method and the bubble sort C + + implementation