-
Notifications
You must be signed in to change notification settings - Fork 457
/
Copy pathSelectionSortalgo.java
70 lines (57 loc) · 1.63 KB
/
SelectionSortalgo.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//selectionsort algorithm-(numbers are sort with selection sort)
package simplesortingapp;
public class Simplesortingapp {
public static void main(String[] args) {
// TODO code application logic here
SimpleSorting k = new SimpleSorting(7);
k.insert(4);
k.insert(8);
k.insert(1);
k.insert(3);
k.display();
k.selectionSort();
k.display();
}
}
class SimpleSorting {
private int[] a;//ref to array a
private int nElems;//number of data items
//------------------------------------------------------
public SimpleSorting(int max) {
this.a = new int[max];
this.nElems = 0;
}
public void insert(int value) {
if (nElems == a.length) {
System.out.println("Array is full");
return;
}
this.a[this.nElems] = value;
this.nElems++;
}
public void display() {
System.out.println("Array content");
for (int i = 0; i < this.nElems; i++) {
System.out.print(this.a[i] + " ");
}
System.out.println();
}
private void swap(int index1, int index2) {
int temp;
temp = a[index1];
a[index1] = a[index2];
a[index2] = temp;
}
public void selectionSort() {
for (int i = 0; i < nElems; i++) {
int minIndex = i;
for (int j = i + 1; j < nElems; j++) {
if (a[j] < a[minIndex]) {
minIndex = j;
}
}
swap(i, minIndex);
}
System.out.println("numbers are sort with selection sort");
}
}