排序算法总结
要找工作了,每次面试都是排序算法,为了准备,我网上找了些快排的源码,郁闷的,每个都出错,为了让所有和我一样郁闷的人不在郁闷,我对排序算法做了个总结,C#版的,不过估计都能看的懂,为了这些算法,我看了2个小时的C++想写个C++版的,无奈,连个数组都不支持:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharp_Console_003.SortAgrithms
{
class Sortor
{
public int[] arr;
/// <summary>
/// selection sort
/// </summary>
public void SelectionSort()
{
int aLength = arr.Length;
int temp;
for (int i = 0; i < aLength; i++)
{
for (int j = i+1; j < aLength; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
/// <summary>
/// Insertion sort
/// </summary>
public void InsertionSort()
{
int aLength = arr.Length;
int temp;
for (int i = 1; i < aLength; i++)
{
if(arr[i-1] > arr[i])
{
temp = arr[i-1];
arr[i-1] = arr[i];
arr[i] = temp;
for (int j = i-1 ; j > 0; j--)
{
if (arr[j] < arr[j - 1])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
continue;
}
}
}
}
/// <summary>
/// 插入排序非替换实现
/// </summary>
public void InsertionSort_1()
{
int aLength = arr.Length;
int temp;
for (int i = aLength - 1; i > 0; i--)
{
if (arr[i] < arr[i - 1])
{
temp = arr[i - 1];
int j;
for (j=i; j < aLength; j++ )
{
if (arr[j] < temp) arr[j - 1] = arr[j];
else break;
}
arr[j-1] = temp;
}
}
}
/// <summary>
/// quick sort
/// </summary>
public void QuickSort(int left, int right)
{
int i = left;
int j = right;
int temp, middle;
middle = arr[left];
while (true)
{
while (arr[i] <= middle && i++ < right-1);
while (--j > left && arr[j] > middle);
if (i > j) break;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
arr[left] = arr[j];
arr[j] = middle;
if (left == i) return;
if (left < j)
QuickSort(left, j);
if (right > i)
QuickSort(i, right);
}
/// <summary>
/// BubbleSort
/// </summary>
public void BubbleSort()
{
int aLength = arr.Length;
int temp;
for (int i = 0; i < aLength ; i++)
{
for (int j = aLength-1; j > i; j--)
{
if (arr[j] < arr[j - 1])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
}
/// <summary>
/// print the array
/// </summary>
public void Print()
{
int aLength = arr.Length;
for (int i = 0; i < aLength; i++)
{
Console.Write(arr[i] + ",");
}
Console.WriteLine();
}
/*
* 还有一种排序算法叫位排序算法,出自编程珠玑第二版,是利用数组的下表来排序
* 不过此排序算法有个缺点就是,只能对不重复的数进行排序,在排列电话号码的时候很有用,也是由此诞生的
*/
}
}
测试部分代码:
……
static void Main(string[] args)
{Sortor sortor = new Sortor();
sortor.arr = new int[] { 4,7,4,8,2,3,8,1,5,4,7,2,1};
//sortor.SelectionSort();
//sortor.InsertionSort();
sortor.InsertionSort_1();
//sortor.QuickSort(0, sortor.arr.Length);
//sortor.BubbleSort();
sortor.Print();
}