Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c2ad1ea

Browse files
author
Ram swaroop
committed
selection sort : done
1 parent 570f39e commit c2ad1ea

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package me.ramswaroop.arrays;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Created by IntelliJ IDEA.
7+
*
8+
* @author: ramswaroop
9+
* @date: 8/22/15
10+
* @time: 12:28 PM
11+
*/
12+
public class SelectionSort {
13+
14+
/**
15+
* Selection Sort.
16+
*
17+
* Explanation:
18+
* This is one of the simplest algorithm where each time the smallest/largest
19+
* element is chosen and placed at the appropriate position and then again the
20+
* logic is applied on rest of the elements till the entire array is sorted.
21+
*
22+
* Time complexity: O(n) for all cases.
23+
*
24+
* NOTE: Advantage of this sort is that it requires minimum number of memory writes
25+
* like Cycle sort.
26+
*
27+
*
28+
* @param a
29+
*/
30+
public static void selectionSort(int[] a) {
31+
int minIndex;
32+
33+
for (int i = 0; i < a.length - 1; i++) {
34+
minIndex = i;
35+
for (int j = i + 1; j < a.length; j++) {
36+
if (a[j] < a[minIndex]) {
37+
minIndex = j;
38+
}
39+
}
40+
swap(a, i, minIndex);
41+
}
42+
}
43+
44+
private static void swap(int[] a, int index1, int index2) {
45+
int temp = a[index1];
46+
a[index1] = a[index2];
47+
a[index2] = temp;
48+
}
49+
50+
public static void main(String a[]) {
51+
int[] ar = new int[]{3, 2, 1, 5, 6, 9, 7, 10};
52+
selectionSort(ar);
53+
System.out.println(Arrays.toString(ar));
54+
55+
ar = new int[]{3, 2, 1, 5, 5, 6, 9, 7, 6, 10};
56+
selectionSort(ar);
57+
System.out.println(Arrays.toString(ar));
58+
}
59+
}

0 commit comments

Comments
 (0)