using System;
namespace Test
{
/// <summary>
/// Summary description for Class1
/// </summary> class Class1
{
static void Main(string[] args)
{
//
// TODO: Add code to start application here.
// //原始資料
int[] Data=new int[]{45, 23, 34, 55, 12,
67, 37, 89, 44, 28};
Console.WriteLine( "[排序前]" );
PrintValues(Data);
Console.WriteLine( "[陣列數] {0}" , Data.Length );
shell_sort(ref Data);
Console.WriteLine( "[排序後]" );
PrintValues(Data);
Console.ReadLine();
}
public static void bubble_sort(ref int[] data) {
//泡泡排序法
int n=data.Length;
for (int pass = 1; pass <= n - 1; pass++)
for (int j = 0; j <= n - 2; j++)
if(data[j] > data[j+1])
swap(ref data[j], ref data[j+1]);
}
public static void bubble_sort2(ref int[] data) {
//泡泡排序法 - 加強版
int n=data.Length;
int flag=0;
for (int pass = 0 ; ( pass <= n-2 ) && ( flag == 0 ) ; pass++) {
flag=1; /* 如果 flag=1 代表 j 迴圈內未作任何交換,資料已排序好 */
for (int j = 0; j <= n - pass - 2; j++)
if(data[j] > data[j+1]) {
swap(ref data[j], ref data[j+1]);
flag=0;
}
}
}
public static void exchange_sort(ref int[] data) {
//交換排序法
int n=data.Length;
for (int i=0; i<= n-2; i++)
for(int j = (i+1); j <= n-1; j++)
if (data[i] > data[j])
swap(ref data[i], ref data[j]);
}
public static void select_sort(ref int[] data) {
//選擇排序法
int n=data.Length;
int small; /* 記錄最小數的index值 */
for (int i=0; i<= n-2; i++) {
small=i;
for(int j = (i+1); j <= n-1; j++)
if (data[small] > data[j]) small=j;
swap(ref data[i], ref data[small]);
}
}
public static void insert_sort(ref int[] data) {
//插入排序法
int n=data.Length;
int i,j,temp;
for (i = 1; i < n; i++) {
temp = data[i];
for (j = (i - 1); (j >= 0) && (data[j] > temp) ; j--)
data[j+1] = data[j];
data[j+1] = temp;
}
}
public static void shell_sort(ref int[] data) {
//謝爾排序法 - 改良的插入排序法
int n=data.Length;
int i,j,x,hcount,hgroup;
//hcount:每個群組的間隔
for ( hcount=2; hcount <(n/2) ; hcount=hcount*2) {
//對個別的群組作插入排序法
for ( hgroup=1;hgroup <= hcount-1; hgroup++) {
//插入排序法
for (i=hgroup;i<=n-1;i+=hcount) {
x=data[i];
j=i-hcount;
while (j>=0 && data[j]>x) {
data[j+hcount]=data[j];
j-=hcount;
}
data[j+hcount]=x;
}
}
}
//最後再作一次插入排序法
for (i = 1; i <= n-1; i++) {
x = data[i];
j=i-1;
while (j>=0 && data[j]>x) {
data[j+1] = data[j];
j--;
}
data[j+1] = x;
}
}
public static void swap(ref int a, ref int b) {
int t;
t = a;
a = b;
b = t;
}
public static void PrintValues( Object[] myArr ) {
foreach ( Object i in myArr ) {
Console.Write( "{0} - ", i );
}
Console.WriteLine();
}
public static void PrintValues( int[] myArr ) {
foreach ( int i in myArr ) {
Console.Write( "{0} - ", i );
}
Console.WriteLine();
}
}
}
C# - 排序演算法
on
0 意見:
張貼留言
注意:只有此網誌的成員可以留言。