This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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
Author

Selection Sort?

Hugh Mclaughlin
Greenhorn

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
Greenhorn

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?

Layne


Java API Documentation
The Java Tutorial
Hugh Mclaughlin
Greenhorn

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 follows...it's a lot easier!



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

Arrays.sort(deck);
Hugh Mclaughlin
Greenhorn

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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Selection Sort?