代碼
int[] source = new int[] { 1, 34, 3, 45, 3 };
printInt(source);
//從小到大排序
/* //選擇
for (int i = 0; i < source.Length; i++)
{
for (int j = i + 1; j < source.Length; j++)
{
//前面的比後面的大,則調換位置
if (source[i] > source[j])
{
int temp = source[i];
source[i] = source[j];
source[j] = temp;
}
}
}*/
/* //冒泡
int j = 1;
bool done = false;
while(j<source.Length && !done)
{
done = true;
for (int i = 0; i < source.Length-1; i++)
{
//[相鄰的倆比較]前面的比後面的大,則調換前後位置
if (source[i] > source[i+1])
{
done =false;
int temp = source[i];
source[i] = source[i+1];
source[i+1] = temp;
}
}
j++;
}*/
//插入法排序
for (int i = 1; i < source.Length ; i++)
{
int temp = source[i];
int j = i;
while (j>0 && source[j-1]>temp)
{
source[j] = source[j - 1];
j--;
}
source[j] = temp;
}
測試下排序.
1。數組定義,並初始化int[] source = new int[] { 1, 34, 3, 45, 3 };
2。列印數組,用for迴圈列印
3。排序思想[以從小到大為例]
(1)i=0;i<長度;i++ ; { j =i+1;j<長度;j++ .拿第i個與第i之後的所有(j)依次比較,若i處大於後者,則調換位置----一輪下來,i處放的是未排序的數值中最小的.--稱選擇排序
(2)j=1;flag=fasle while(j<長度且flag為false){for(i=1;i<長度-1;i++) 哪相鄰的倆(i與i+1)比較,小的放前面----一輪下來,最大的被放到了最後.---稱為冒泡排序
(3)i=1;i<長度,i+{記下i處值,j=i while(i之前(j處)若有比i處大的,則讓i處值等於較大的 ) j處等於i處值原始值----一輪下來,i處是已排序的i個值中最大的--稱插入排序