class Program { static void Main(string[] args) { int[] array = new[] { 234, 632, 23, 643, 2, 6, -2, 423, 2342,43 }; Console.WriteLine("排序前:"); Console.WriteLine(string.Join(",", array)); InsertSort(array); Console.WriteLine("排序後:"); Console.WriteLine(string.Join(",", array)); Console.ReadKey(); } /// <summary> /// 直接插入排序 /// </summary> /// <param name="sources">目標數組</param> private static void InsertSort(int[] sources) { // 從索引1開始,假設sources[0]已經有序 for (int i = 1, len = sources.Length - 1; i <= len; i++) { // 准備要插入的數據 int insertValue = sources[i], // 假設要插入的索引 insertIndex = i - 1; // 遍歷查找插入的索引位置 while (insertIndex >= 0 && insertValue < sources[insertIndex]) { // 當前數據後移一位 sources[insertIndex + 1] = sources[insertIndex]; insertIndex--; } // 不滿足以上條件,說明找到位置,插入數據 sources[insertIndex + 1] = insertValue; } } /// <summary> /// 直接插入排序 for實現 /// </summary> /// <param name="sources">目標數組</param> private static void InsertSort1(int[] sources) { for (int i = 1, len = sources.Length - 1; i <= len; i++) { for (int j = i; j > 0; j--) { if (sources[j] > sources[j - 1]) // > 降序, < 升序 { int temp = sources[j]; sources[j] = sources[j - 1]; sources[j - 1] = temp; } } } } }
6, 18, 28, 93, 46, 55
6, 18, 28, 93, 46, 55
6, 18, 28, 93, 46, 55
6, 18, 28, 46, 93, 55
6, 18, 28, 46, 55, 93
#include <iostream>
using namespace std;
void qsort(int array[],int size)
{
int z=0,y=size-1;
int k=array[z];
if(z<y)
{
do
{
while((z<y)&&(array[y]>=k)) y--;
if(z<y)
{
array[z]=array[y];
z++;
}
while((z<y)&&(array[z]<=k)) z++;
if(z<y)
{
array[y]=array[z];
y--;
}
}while(z!=y);
array[z]=k;
qsort(array,z);
qsort(array+z+1,size-z-1);
}
}
int main()
{
int n,i;
cin >> n;
int *a=new int[n+1];
for(i=0;i<n;i++) cin >> a[i];
qsort(a,n);
for(i=0;i<n;i++) cout << a[i] << ' ';
cout << endl;
system("pause");
return 0;
}