Each written test, 80% of the written test will always mention bubble sort.
Write a version of the section first:
// [Bubble sort] Details: Inner loop NOTE!!! int array[] = {3, 2, 5, 9, 7, 6}; int length = sizeof (Array) / sizeof (array[0]); for (int i = 0 ; i < length - 1; i ++) { for ( int j = 0; j < length - 1 - i ; j ++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } for ( int i = 0; i < length; i ++) { printf ("%d", array[i] ); }
After reading the interviewer, he said a sentence, if it is an orderly array, then this efficiency is not reduced?
I changed it again.
for (int i = 0 ; i < length - 1; i ++) { int flag = 0; for (int j = 0 ; j < length - 1 - i; j ++) { if (array[j] > array[j + 1]) { swap (array + j, ARRAY&NBSP;+&NBSP;J&NBSP;+&NBSP;1); flag ++; } } printf ("%d\n" , flag); if (flag == 0) { break; } }
After reading it, he said, it would be easier ... This is killing me ... Think for a long while did not think, he finally showed me is such a string of code, feel benefited to write down.
int flag = 1; for (int i = 0 ; i < length - 1 && 1 == flag; i ++) { flag = 0; for (int j = 0; j < length - 1 - i; j ++) { if ( ARRAY[J]&NBSP;>&NBSP;ARRAY[J&NBSP;+&NBSP;1]) { swap (array + j, array + j + 1); flag = 1; } } }
Bubble sort of questions on IOS face