C#中的三个排序,冒泡/选择/插入

定义一个一维数组

int[] px = { 1, 23, 4, 3, 67, 68, 79, 56, 1213, 323, 234, 34 };

            // 冒泡排序
             int temp2 = 0;
             for(int i = 0; i < px.Length; i++)
             {
                 for(int j = i+1; j < px.Length; j++)
                 {
                     if (px[i] > px[j])//从小到大
                     {
                         temp2 = px[i];
                         px[i] = px[j];
                         px[j] = temp2;
                     }
                 }
             }
             //选择排序
             int n ;
             for(int i = 0; i < px.Length; i++)
             {
                 n = i;
                 for(int j = i+1; j < px.Length; j++)
                 {
                     if (px[n] > px[j])//从小到大
                     {
                         n = j;
                     }
                 }
                 int temp = px[n];
                 px[n] = px[i];
                 px[i] = temp;
             }
             //插入排序
             int temp = 0;


             for(int i = 0; i < px.Length; i++)
             {
                 temp = px[i];
                 int n = i - 1;//与待排序元素值作比较的元素的下标 
                while (n >= 0 && px[n] > temp)
                {
                     px[n + 1] = px[n];
                         n--;
                }
                 px[n + 1] = temp;//找到了插入位置,插入待排序元素
             }

//遍历数组
             for (int i = 0; i < px.Length; i++)
             {
                 Console.Write(px[i]+" ");
             }
             Console.ReadKey();

猜你喜欢

转载自blog.csdn.net/qq_39374899/article/details/80819893