Bubble sort, that should be the simplest. Give a set of unordered arrays, and how to sort them. For example, 2, 3, 7, 1, 6 This set of data, to be in order from small to large. The first idea is to compare the first number A to the subsequent number if the subsequent number is larger, then the order of the two numbers is correct. Updates the current A to the larger number later, and then to the later comparison. Encounter smaller than oneself to exchange, but do not update a.
As an example:
1. First comparison, 2:3 small, after execution 2, 3, 7, 1, 6
2. Second comparison, 3:7 small, after execution 2, 3, 7, 1, 6
3. Third comparison, 7:1 large, after execution 2, 3, 1, 7, 6
4. Fourth comparison, 7:6 large, after execution 2, 3, 1, 6, 7
In this way, the largest number is bubbled to the end of the array successfully by a single traversal.
////main.cpp//Bubblesort////Created by madmarical on 15/11/19.//Copyright (c) 2015 COM. All rights reserved.//#include<iostream>using namespacestd;voidBubblesort (int* PData,intlength) { inttemp; for(inti =0; I! = length;++i) { for(intj =0; J! = length; ++j) {if(Pdata[i] <Pdata[j]) {Temp=Pdata[i]; Pdata[i]=Pdata[j]; PDATA[J]=temp; } } }}voidPrintint* PData,intlength) { for(inti =0; I! = length; ++i) {cout<<pData[i]<<" "; } cout<<Endl;}intMainintargcConst Char*argv[]) { intPdata[] = {2,3,7,1,6}; Bubblesort (PData,5); cout<<"The result is:"; Print (PData,5); return 0;}
Operation Result:
The result is:1 2 3 6 7
Reflection:
1. Why do I need to use pointer parameters?
Because the function return value cannot be an array, you can only set the function of an empty type, how can the parameter change the value of the argument? Pointer parameters are the best choice.
2. How efficient is this sort?
Each number requires a full set of traversal, so when the array length is n, a n*n traversal operation is required. Time Efficiency Upper O (n^2). However, we use a very small number of variables, only one temp to save a value, so the space complexity of O (1).
C + + bubble sort