Text description
First the first record's keyword and the second record's keyword are compared, if in reverse order (L.r[1].key>l.r[2].key), two records are exchanged for the location, and then the second record and the third record's keywords are compared. And so on, until the n-1 record and the nth record have been compared by a keyword. The process described above is called the first bubbling sort, and the result is that the largest record of the keyword is placed in the position of the last record.
The entire foaming sequencing process requires K (k is greater than or equal to 1 and less than N), and obviously the conditions for determining the end of the bubble sort should be the operations that have not exchanged records during the sorting process.
Algorithm analysis
If the sequence to be sorted is a "positive sequence" sequence, only one trip is ordered, and the comparison between n-1 keywords is performed during the sorting process, and the records are not moved;
If the sequence to be sorted is an "inverse" sequence, a n-1 order is required, with n (n-1)/2 comparisons and record movements of the order of magnitude.
Therefore, the total time complexity is n*n, and the auxiliary space is 1, which is a stable sorting method.
Code implementation
1#include <stdio.h>2#include <stdlib.h>3 4 #defineDEBUG5 6 #defineEQ (A, B) ((a) = = (b))7 #defineLT (A, B) ((a) < (b))8 #defineLQ (A, B) ((a) <= (b))9 Ten #defineDEBUG One A #defineMAXSIZE 20 -typedefintKeyType; -typedefCharInfoType; thetypedefstruct{ - KeyType key; - InfoType Otherinfo; - }redtype; + -typedefstruct{ +Redtype r[maxsize+1]; A intlength; at }sqlist; - - voidprintlist (sqlist L) { - inti =0; -printf"Subscript Value:"); - for(i=0; i<=l.length; i++){ inprintf"[%d]", i); - } toprintf"\ n Keyword:"); + for(i=0; i<=l.length; i++){ -printf"%-3d", L.r[i].key); the } *printf"\ n Other values:"); $ for(i=0; i<=l.length; i++){Panax Notoginsengprintf"%-3c", l.r[i].otherinfo); - } theprintf"\ n"); + return ; A } the + /*Bubble Sort*/ - voidBubblesort (SqList *L) $ { $ inti =0, j =0, Isswap =0; - redtype tmp; - for(i=1; i<=l->length; i++){ theIsswap =0; - for(j=1; j< (l->length-i+1); J + +){Wuyi if(! LQ (L->r[j].key, l->r[j+1].key)) { theTMP = l->R[j]; -L->R[J] = l->r[j+1]; Wul->r[j+1] =tmp; -Isswap =1; About } $ } - #ifdef DEBUG -printf"bubble sort%d times: \ n", i); -Printlist (*L); A #endif + if(!Isswap) the Break; - } $ } the the intMainintargcChar*argv[]) the { the if(ARGC <2){ - return-1; in } the sqlist L; the inti =0; About for(i=1; i<argc; i++){ the if(i>MAXSIZE) the Break; theL.r[i].key =atoi (Argv[i]); +L.r[i].otherinfo ='a'+i-1; - } theL.length = (I-1);Bayil.r[0].key =0; thel.r[0].otherinfo ='0'; theprintf"input data: \ n"); - printlist (L); -Bubblesort (&L); the return 0; the}
Bubble Sort
Run
Bubble sorting, sort by exchange, internal sort