File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Selection Sort? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Selection Sort?" Watch "Selection Sort?" New topic

Selection Sort?

Hugh Mclaughlin

Joined: Nov 18, 2004
Posts: 24
I'm sure plenty of you have heard of the age old Card Sort problem....sort a deck of cards from small to large.

I've chosen to use a For Count with the followin set up:

1. For count assigned 1 to 51 //outer loop
2. smallestCount = count
3. For currentCard assigned count+1 to 52 //inner loop
4. If deck[currentCard] < deck[smallestCard]
5. smallestCard = currentCard
6. If smallestCard != count //you need to swap
7. Swap deck[count] and deck[smallestCard]

I can manage the first outer loop could anyone give me a hand with the inner loop code? I figure apart from the class and app, i need the Math class for random numb generation and integer class for the array!

many thanks!
Hugh Mclaughlin

Joined: Nov 18, 2004
Posts: 24
oh and here is the main part of my code so far:

// Random number generator

Random rgen = new Random();
int[] cards = new int[52];

//Initialize the array to the ints 0-51

for (int i=0; i<52; i++) {
cards[i] = i;

//Shuffle by exchanging each element randomly

for (int i=0; i<52; i++) {
int randomPosition = rgen.nextInt(52);
int temp = cards[i];
cards[i] = card[randomPosition];
cards[randomPosition] = temp;
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
The pseudocode you posted above seems quite straightforward to me. Can you translate each line in it to a single line of Java code? If not, what parts do you not understand?


Java API Documentation
The Java Tutorial
Hugh Mclaughlin

Joined: Nov 18, 2004
Posts: 24
Well to be honest I am completely stuck on the code, if anyone could possibly write for me I'd be happy to reward them via PayPal!! So I could compare it to the Pseudocode and learn! Many thanks.
Ed Lance
Ranch Hand

Joined: Aug 02, 2000
Posts: 38
Here's a simple sort example. NOTE - check out the second method that's a lot easier!

OR EVEN BETTER..the following sorts an array in natural order,
there's a lot of overloaded versions

Hugh Mclaughlin

Joined: Nov 18, 2004
Posts: 24
So would this require a class and an application class, or just an app? are the fields as follows?

private int x;
private int smallestCard;
private int currentCard;
private int tmpCard;
private int i;

many thanks
I agree. Here's the link:
subject: Selection Sort?
It's not a secret anymore!