Basic Sorting Algorithms
1.An Array Class Test Bed
class CArray { private int [] arr; private int upper; private int numElements; public CArray(int size) { arr = new int[size]; upper = size-1; numElements = 0; } public void Insert(int item) { arr[numElements] = item; numElements++; } public void DisplayElements() { for(int i = 0; i <= upper; i++) Console.Write(arr[i] + " "); } public void Clear() { for(int i = 0; i <= upper; i++) arr[i] = 0; numElements = 0; } } static void Main() { CArray nums = new CArray(); for(int i = 0; i <= 49; i++) nums.Insert(i); nums.DisplayElements(); } }
2.Bubble Sort
public void BubbleSort() { int temp; for(int outer = upper; outer >= 1; outer--) { for(int inner = 0; inner <= outer-1;inner++) if ((int)arr[inner] > arr[inner+1]) { temp = arr[inner]; arr[inner] = arr[inner+1]; arr[inner+1] = temp; } } }
3.SelectionSort
public void SelectionSort() { int min, temp; for(int outer = 0; outer <= upper; outer++) { min = outer; for(int inner = outer + 1; inner <= upper; inner++) if (arr[inner] < arr[min]) min = inner; temp = arr[outer]; arr[outer] = arr[min]; arr[min] = temp; } }
4.InsertionSort
public void InsertionSort() { int inner, temp; for(int outer = 1; outer <= upper; outer++) { temp = arr[outer]; inner = outer; while(inner > 0 && arr[inner-1] >= temp) { arr[inner] = arr[inner-1]; inner -= 1; } arr[inner] = temp; } }
课后练习:
作 者:doku
出 处:http://www.cnblogs.com/kulong995/
关于作者:喜欢编程,喜欢美食,专注于.NET项目开发。
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!