Test interview series --- sort algorithm album --- bubble sort --- incorrect answer correction
Original answer:
# Include
# Define LEN 10 // ARRAY length void main (void) {int ARRAY [10] = {0, 6, 3, 2, 7, 5, 4, 9, 1, 8}; // printf ("\ n"); for (int a = 0; a <LEN; a ++) // print the ARRAY content {printf ("% d", ARRAY [a]) ;}int I = 0; int j = 0; bool isChange; // set the exchange flag for (I = 1; I <LEN; I ++) {// do the most LEN-1 sort isChange = 0; // before the start of this sort, the exchange flag should be false for (j = LEN-1; j> = I; j --) // for the current unordered partition ARRAY [I .. LEN] Bottom-up scan {if (ARRAY [j + 1] <ARRAY [j]) {// exchange Record ARRAY [0] = RRAY [j + 1]; // ARRAY [0] is not a sentry, only a temporary storage unit ARRAY [j + 1] = ARRAY [j]; ARRAY [j] = ARRAY [0]; isChange = 1; // The exchange flag is set to true due to exchange.} printf ("\ n "); for (a = 0; a <LEN; a ++) // print the ARRAY content after this sorting {printf ("% d", ARRAY [a]);} if (! IsChange) // This sorting has not been exchanged. Terminate the algorithm {break ;}} printf ("\ n"); return;} in advance ;}
Train of Thought Analysis: Compare the size of adjacent images one by one from the sequence header, and obtain the maximum or minimum number at the end of the sequence. Then compare the remaining n-1 numbers one by one according to the above method. Finally, the sorting is completed. Error Analysis: an error at for (I = 1; I <LEN-1; I ++) causes ARRAY [0] Not to be sorted. For (a = 0; a <LEN; a ++) does not return the life type of local variable.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>> Corrected answer:
# Include
# Include
# Include
Using namespace std; # define LEN 10 int _ tmain (int argc, _ TCHAR * argv []) {int ARRAY [10] = {0, 6, 3, 2, 7, 5, 4, 9, 1, 8}; // The array to be sorted for (int a = 0; a <LEN; a ++) // print the ARRAY content {printf ("% d", ARRAY [a]);} int I = 0; int j = 0, temp = 0; bool isChange; // set the exchange flag for (I = 0; I <LEN-1; I ++) {// do the most LEN-1 trip sort isChange = 0; // before the start of this sort, the exchange flag should be false for (j = LEN-1; j> = I; j --) // for the current unordered partition ARRAY [I .. LEN] Bottom-up scan {if (ARRAY [j] <ARRAY [J-1]) {// exchange Record temp = ARRAY [j]; // temp do save unit ARRAY [j] = ARRAY [J-1]; ARRAY [J-1] = temp; isChange = 1; // The switch flag is set to true} printf ("\ n"); for (int a = 0; a <LEN; a ++) // print the ARRAY content after this sorting {printf ("% d", ARRAY [a]);} if (! IsChange) // This sorting has not been exchanged, early termination of the algorithm {break ;}} printf ("\ n"); return 0 ;}
Correction analysis: temp is used to replace ARRAY [0] for data transfer; Sorting starts from ARRAY [0. Output after correction: