C Implementation Bubble Sorting Algorithm Code Example

  • 2021-10-24 23:31:39
  • OfStack

1. Principle: Compare array [index] and array [index+1] in pairs from the first position of the array. If array [index] is greater than array [index+1], exchange the positions of array [index] and array [index+1] until the end of the array;
Starting from the first position of the array, repeat the above actions until the array length is minus 1 position;
Starting from the first position of the array, repeat the above actions until the array length is minus 2 positions;
. . . .
2. Time complexity: O (N & sup2; (n-1) * (n-2)...... = n* (n-1)/2 comparisons and the number of exchanges about 1.5 times of comparisons (in average case), then the time complexity according to the large O notation is O (N ^ 2)
3. Code example:


using System;
namespace MySort
{
  // Establish first 1 Class, and put all sorting methods into this class in the future. 
  public class SumSort
  {
    // Bubble sorting method, from small to large, although many bubble sorting are from large to small, 
    // But that's what I want. What can you do to me? 
    public void PopSort(int[] list)
    {
      int i, j, temp;  // Define first 1 Variables to be used under 
      for (i = 0; i < list.Length - 1; i++)
      {
        for (j = i + 1; j < list.Length; j++)
        {
          if (list[i] > list[j]) // If the 2 The number is less than the number 1 Number 
          {
            // Swap the positions of two numbers, and you can also write them separately here 1 Exchange methods, just call them here 
            temp = list[i]; // Put the big numbers in 1 Temporary storage locations 
            list[i] = list[j]; // Then assign the smaller number to the front 1 To ensure that the front of each sort is the smallest 
            list[j] = temp; // Then assign the large number of the temporary position to the post 1 A 
          }
        }
      }
    }
  }
  public class test
  {
    // Here for 1 Group test data and print out to see how the sorting method works 
    static void Main()
    {
      int[] arr = { 1, 4, 2, 43, 5, 61, 89, 34, 67, 32, 40 };
      // Instantiate the data sorting class 1 Then call the method. 
      // What? I need to instantiate it, but what if I don't want to instantiate it? 
      // It doesn't matter, put PopSort Method preceding 1 A static That calls directly SumSort.PopSort(arr) It would be good 
      SumSort mysort = new SumSort();
      // Come on, let's line up according to height, the short one is in front of the high one is behind 
      mysort.PopSort(arr);
      // How obedient, look at everyone's ranking 
      for (int i = 0; i < arr.Length; i++)
      {
        Console.Write(" No. 1 {0} Bit is {1}\n", i + 1, arr[i]);
      }
      Console.WriteLine();
    }
  }
}



Related articles: