Results 1 to 2 of 2
Thread: selection sort
- 04-28-2009, 05:20 PM #1
Member
- Join Date
- Dec 2008
- Posts
- 39
- Rep Power
- 0
selection sort
I have to create a random array of ints[]. Then I have to sort the array of ints using a selection sort. I cant seem to figure out what im doing wrong with my code. If anyone could help I would greatly appreciate it. Thanks
import java.util.*;
import java.io.*;
public class RandomInts
{
private static final int SIZE = 10;
Random ran = new Random();
int[] a = new int[SIZE];
public void random(){
for(int i = 1; i < a.length; i++){
a[i]= (int)(Math.random() * 100);
System.out.println(a[i]);
}
System.out.println("\n");
}
public void selectionSort() {
for (int i=0; i<a.length-1; i++) {
int min = i;
for (int j=i+1; j<a.length; j++) {
if (a[min] > a[j]) {
min = j;
}
}
if (min != i) {
int temp = a[i];
a[i] = a[min];
a[min] = temp;
System.out.println(a[min]);
}
}
}
public static void main(String[] args){
RandomInts b = new RandomInts();
b.random();
b.selectionSort();
}
}
That is the code I have so far and this is what it prints out:
30
54
50
83
28
20
23
59
91
30
54
50
83
83
83
It needs to print from largest to smallest smallest to largest.
thanks
- 04-29-2009, 12:40 AM #2
nothing is wrong, you need to print the output in main() NOT inside the sorting loop.
USE CODE TAGS--> [CODE]...[/CODE]
Get NotePad++ (free)
Similar Threads
-
Using Merge Sort to sort an ArrayList of Strings
By coldfire in forum New To JavaReplies: 3Last Post: 03-13-2009, 01:03 AM -
How to change Bubble+Selection+Insertion Sorts to Sort String Values?
By VinceGuad in forum New To JavaReplies: 3Last Post: 01-26-2009, 12:20 AM -
write a selection sort without having numerous variable?
By seandingobat in forum New To JavaReplies: 6Last Post: 10-28-2008, 02:33 PM -
How to sort a list using Bubble sort algorithm
By Java Tip in forum AlgorithmsReplies: 3Last Post: 04-29-2008, 08:04 PM -
Selection sort in Java
By Java Tip in forum AlgorithmsReplies: 0Last Post: 04-15-2008, 07:41 PM
Bookmarks