搜尋此網誌

2012年3月24日 星期六

Recursive Selection Sort (遞迴選擇排序法)

維護舊有Java程式專案
1:  public class RecursiveSelectionSort {  
2:      public static void main(String[] args) {  
3:          int [] array ={5,2,3,6,1,7,0,9,100,4,8};  
4:          selectionSort(array, array.length);  
5:          for(int i=0;i<array.length;i++){  
6:              System.out.print(array[i]+" ");  
7:          }  
8:      }  
9:      /**  
10:       * Using the concept of selection sort.  
11:       * Implemented by an iterative and a recursive mechanisms.  
12:       *   
13:       * Following are steps:  
14:       * 1.Finding the smallest one and its index;  
15:       * 2.Put the smallest into the right end side;  
16:       * 3.Decrease the array size;  
17:       * Recursively calling this method.  
18:       *   
19:       * @param array unsorted array  
20:       * @param length array length  
21:       */  
22:      public static void selectionSort(int[] array , int length) {  
23:          if(length > 0){  
24:              int smallestIdx = 0 ;  
25:              int smallest = array[smallestIdx];  
26:              //1.From left to right find the smallest one and its index;  
27:              for(int i =0 ;i<length ;i++){  
28:                  if(array[i]< smallest){  
29:                      smallest = array[i];  
30:                      smallestIdx = i;  
31:                  }  
32:              }  
33:              //2.Put the smallest into the right end side;  
34:              swapElements(array,smallestIdx,length -1);  
35:              //3.Decrease the array size;  
36:              length -=1;  
37:              //4.Recursively calling this method.  
38:              selectionSort(array,length);  
39:          }  
40:      }  
41:      private static void swapElements(int[] array, int idx, int idx1) {  
42:          int tmp = array[idx];  
43:          array[idx] = array[idx1];  
44:          array[idx1] = tmp;  
45:      }  
46:  }  

沒有留言:

張貼留言