Before writing to several sort of algorithms, for example:
//Bubble SortvoidBubblesort (unsignedChar*list,intlength) { inti,j,temp; for(i =0; i < length; i++) { for(j =0; J < Length-i-1; J + +) { if(list[j+1] <List[j]) {Temp= List[j +1]; List[j+1] =List[j]; LIST[J]=temp; } } }}
The original operation is the exchange of data, the algorithm Time review degree is O (n^2).
But if we need to sort the data such as: (1 2 3 5 6 9) or simply swap a few times to sort well such as (2 1 3 5 6 9), the loop behind the algorithm is not working hard at all.
At this point we just need to add a flag to avoid the situation.
//Bubble SortvoidBubblesort (unsignedChar*list,intlength) { inti,j,temp; intFlag; for(i =0, flag =1; I < length && flag; i++) {flag=0; for(j =0; J < Length-i-1; J + +) { if(list[j+1] <List[j]) {Temp= List[j +1]; List[j+1] =List[j]; LIST[J]=temp; Flag=1; } } }}
When the sequence itself is correct, in the best case: The time Review degree is O (n).
Related: Views on data and structure
An improved sorting algorithm