Fork me on GitHub

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; 
                            } 
                         } 

 

 课后练习:

https://files.cnblogs.com/kulong995/ExercisesThree.rar

posted @ 2010-01-22 22:01  idoku  阅读(170)  评论(0编辑  收藏  举报