Bubble sort of questions on IOS face

Source: Internet
Author: User

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;&GT;&NBSP;ARRAY[J&NBSP;+&NBSP;1])  {                 swap (array + j, array + j + 1);                 flag =  1;            }         }    } 


Bubble sort of questions on IOS face

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.