Reputation: 3
I'm learning how to implement selection sort
.
What I expected from the code is an ascending order output, like: {1,3,4,5,6,7,9}
But the console showed: 9, 4, 1, 6, 5, 3, 7, 9, 7, 1, 4, 5, 3, 6, 9, 7, 6, 1, 4, 3, 5, 9, 7, 6, 5, 1, 3, 4, 9, 7, 6, 5, 4, 1, 3, 9, 7, 6, 5, 4, 3, 1
What am I supposed to change to get the correct result?
This is my code:
public static void main(String[] args) {
int[]arr = {4,6,1,9,5,3,7};
for(int i = 0; i<arr.length-1; i++) {
for(int j = i+1; j<arr.length; j++) {
if(arr[i]<arr[j]) {
int a=arr[i];
arr[i]=arr[j];
arr[j]=a;
}
}
for (int b = 0; b <arr.length; b++) {
System.out.print(arr[b] + ", ");
}
}
Upvotes: 0
Views: 98
Reputation: 49
Selection Sort - java code
class selectionsort{
public static void sort(int[] arr){
int temp,min;
for(int i=0;i<arr.length;i++)
{
min=i;
for(int j=i+1;j<arr.length;j++)
{
if(arr[min]>arr[j])
{
min=j;
}
}
temp=arr[min];
arr[min]=arr[i];
arr[i]=temp;
}
}
public static void main(String [] args){
int ar[]={4,6,1,9,5,3,7};
sort(ar);
System.out.print("After sort :");
for(int j=0;j<ar.length;j++){
System.out.print(ar[j]+" ");
}
}
}
Upvotes: 0
Reputation: 9344
There is an easier way with Arrays.sort(arr)
public static void main(String[] args) {
int[] arr = {4,6,1,9,5,3,7};
Arrays.sort(arr);
System.out.print(Arrays.toString(arr));
}
}
Upvotes: 0
Reputation: 2727
You are printing the array while you are doing the sorting. Instead, print the array when you are done with the sorting -
public static void main(String[] args) {
int[] arr = {4, 6, 1, 9, 5, 3, 7};
for (int i = 0; i < arr.length - 1; i++) { // first loop
for (int j = i + 1; j < arr.length; j++) { // nested loop
if (arr[i] < arr[j]) { // if condition
int a = arr[i];
arr[i] = arr[j];
arr[j] = a;
} // if condition ends
} // nested loop ends
} // first loop ends
// Now the array is sorted, it's good to print.
for (int b = 0; b < arr.length; b++) {
System.out.print(arr[b] + ", ");
}
}
There is one more catch. Though your sorting would work, your implementation is not really selection sort
. It's bubble sort
implementation. The key difference is, in selection sort
you need to find the min value and place it in the ith
position for every i
. So you only swap once per iteration. In bubble sort, we swap repeatedly like you did.
Also, as pointed out in the comment, for ascending order, you have to flip to condition for swapping. So the correct implementation would be -
public static void main(String[] args) {
int[] arr = {4, 6, 1, 9, 5, 3, 7};
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
int tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
for (int b = 0; b < arr.length; b++) {
System.out.print(arr[b] + ", ");
}
}
Upvotes: 2