学习C#中基本的排序算法
1、冒泡排序法
冒泡排序的思想是:
两两比较相邻记录的关键码,如果反序则交换,直到没有反序的记录为止。
代码如下:
using System;
using System.Collections;
namespace system2
{
class Program
{
static void Main(string[] args)
{
test o = new test();
int[] a = o.put();
int[] b = a;
o.a(a);
Console.ReadLine();
}
}
public class test
{
public int[] put()//输入
{
Console.WriteLine("请输入待排序数组:");
string str = Console.ReadLine();
string[] str1 = str.Split(",");
int[] arr = new int[str1.Length];
for (int i = 0; i < str1.Length; i = i + 1)
{
arr[i] = Convert.ToInt16(str1[i]);
}
return arr;
}
public void a(int[] arr)//冒泡排序
{
int exchange = arr.Length - 1;
int bound;
int temp;
int a = 0, b = 0;
while (exchange != 0)
{
bound = exchange;
exchange = 0;
for (int i = 0; i < bound; i = i + 1)
{
a = a + 1;
if (arr[i] > arr[i + 1])
{
b = b + 1;
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
exchange = i;
}
}
}
Console.WriteLine("排序后为:");
foreach (int s in arr)
{
Console.Write("{0}\t", s);
}
Console.WriteLine("遍历次数为:{0},调换次数为:{1}", a, b);
}
}
}
2、快速排序法
快速排序的基本思想是:
通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此使整个数据变成有序序列。
using System;
using System.Collections;
namespace system2
{
class Program
{
static void Main(string[] args)
{
test o = new test();
int[] b = o.put();
o.quick(b, b.Length);
Console.ReadLine();
}
}
public class test
{
public int[] put()//输入
{
Console.WriteLine("请输入待排序数组:");
string str = Console.ReadLine();
string[] str1 = str.Split(",");
int[] arr = new int[str1.Length];
for (int i = 0; i < str1.Length; i = i + 1)
{
arr[i] = Convert.ToInt16(str1[i]);
}
return arr;
}
public void swap(int[] arr,int x,int y)
{
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public void sort(int[] arr,int start,int end)
{
if (start >= end)
{
return;
}
int mid = arr[end];
int left = start, right = end - 1;
while (left < right)
{
while (arr[left] < mid && left < right)
{
left = left + 1;
}
while (arr[right] >= mid && left < right)
{
right = right - 1;
}
swap(arr, left, right);
}
if (arr[left] >= arr[end])
{
swap(arr, left, end);
}
else
{
left = left + 1;
}