C # Bubble Sorting Optimization

Source: Internet
Author: User

C # Bubble Sorting Optimization

I previously wrote an implementation of C #'s Bubble sorting. Since the previous version was implemented using a two-layer for loop, there is still room for further optimization in sorting this version.

Previous sorting:

int temp = 0;            for (int i = arr.Length - 1; i > 0; i--)            {                for (int j = 0; j < i; j++)                {                    if (arr[j] > arr[j + 1])                    {                        temp = arr[j + 1];                        arr[j + 1] = arr[j];                        arr[j] = temp;                    }                }            }
As can be seen, because there are two for loops, the entire sorting must be performed (n-2 )! Secondary judgment, even if the first generated array is sorted.

To optimize the Bubble Sorting of this version:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; Bubble Sorting of namespace _ 0301 array _ optimization {class Program {static void Main (string [] args) {int len = 0; // array size int min = 0; // int max = 0 for the lower boundary of the array; // Console for the upper boundary of the array. writeLine ("a random array will be generated below"); // receives the array size do {Console. writeLine ("Enter the array size, which must be a positive integer smaller than or equal to 10:"); len = int. parse (Console. readLine ();} while (len <= 0) | (Len> 10); // receives the lower bound Console of the array. writeLine ("Enter the lower bound of the array, which must be an integer:"); min = int. parse (Console. readLine (); // receives the upper bound do {Console of the array. writeLine ("Enter the upper limit of the array, which must be an integer and be larger than the minimum value of the array, and can accommodate the number of {0}:", len); max = int. parse (Console. readLine ();} while (max <= min) | (max-min + 1) <len); Console. writeLine (); Console. writeLine ("array length: {0} \ n lower bound of the array: {1} \ n upper bound of the array: {2}", len, min, max); Console. writeLine ("the generated array is as follows:"); int iSeed = 6; Random ra = new Random (iSeed); int [] arr = new int [len]; // print the value of the original array for (int I = 0; I <arr. length; I ++) {arr [I] = ra. next (min, max); Console. write (arr [I]); if (I <arr. length-1) {Console. write (",");} else {Console. writeLine () ;}// start to sort arrays. Console. writeLine ("array generation is complete, start sorting"); Console. writeLine (); # original region sorting. This sorting must be compared (n-2 )! Times // int temp = 0; // for (int I = arr. length-1; I> 0; I --) // {// for (int j = 0; j <I; j ++) // {// if (arr [j]> arr [j + 1]) // {// temp = arr [j + 1]; // arr [j + 1] = arr [j]; // arr [j] = temp; ///} // # endregion // this sort can be compared at most (n-2 )! Times, but if the current is the optimal sorting result, the comparison int temp = 0; bool swapped = true; do {swapped = false; for (int I = 0; I <arr. length-1; I ++) {if (arr [I]> arr [I + 1]) {temp = arr [I]; arr [I] = arr [I + 1]; arr [I + 1] = temp; swapped = true ;}} while (swapped ); // print the sorted result Console. writeLine ("sorting result:"); for (int I = 0; I <arr. length; I ++) {Console. write (arr [I]); if (I <arr. length-1) {Console. write (",");} else {Console. writeLine () ;}} Console. writeLine ("program ended"); Console. readKey ();}}}
The sorting of this version changes the outer loop to do... while (), and set an identifier variable swapped. If no data replacement is performed in this internal loop, the array sequence has been optimized and the outer loop is ended immediately. This sort can be compared at most (n-2 )! Times, but if the current is the optimal sorting result, the comparison is stopped directly.

In fact, the outer loop can also achieve this effect, but do... while () is more elegant.

Running effect:


Related Article

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.