Tuesday, 20 December 2011

SelectionSort

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class SelectionSort {

 /**
  * @Author Chandrasekhara Kota
  */
 public static void main(String[] args) {
  int arr[]={9,1,8,5,7,-1,6,0,2,2718};
  int sortedArr[]=selectionSort(arr);
  for (int i = 0; i <sortedArr.length; i++) 
  { 
   System.out.println(sortedArr[i]);
  }
 
 }

 private static int[] selectionSort(int[] arr) { 

  int  minIndex, tmp; 
  int n = arr.length; 
  for (int i = 0; i < n - 1; i++) 
  { 
              minIndex = i; 
              for (int j = i + 1; j < n; j++) 
                   if (arr[j] < arr[minIndex]) 
                        minIndex = j; 
              if (minIndex != i) { 
                    tmp = arr[i]; 
                    arr[i] = arr[minIndex]; 
                    arr[minIndex] = tmp; 
              } 
        }
  return arr; 
 }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...