c bubble sort sample share

  • 2020-06-12 10:30:49
  • OfStack

Bubble sort formula:

Ascending order (from small to large) : double for1if; Greater than even; Exchange; Do another for traversal; The outer N - 1; The inner N - 1 - i;

It is more obvious than the above code:


class Program
    {
        static void Main(string[] args)
        {
            int[] array = {1, 3, 5, 7, 90, 2, 4, 6, 8, 10};
            array= GetSort(array);
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write(array[i] + " ");
            }
            Console.ReadKey();
        }
        /// <summary>
        ///  Bubble sort 
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        private static int[] GetSort(int[] array)
        {
            // The outer loop n-1
            for (int i = 0; i < array.Length-1; i++)
            {
                // The inner loop n-1-i
                for (int j = 0; j < array.Length-1-i; j++)
                {
                    if (array[j] > array[j+ 1])
                    {
                        int temp = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = temp;
                    }   
                }
            }
            return array.ToArray();
        }
    }


Related articles: