Results 1 to 7 of 7
- 10-28-2008, 03:05 AM #1
Member
- Join Date
- Sep 2008
- Posts
- 16
- Rep Power
- 0
write a selection sort without having numerous variable?
i'm trying to do a selection sort to sort out an array of unsorted numbers.
basically just trying to swap their position in the index.
for example here:
for( int x = ; x < list.length; x ++){
for( int i = x; i < list.length; i ++){
if( list[x] > list[i] ){
list[x] = list[i];
list[i] = list[x];
}
}
}
return list;
i know that this is wrong, but i hope you get the idea. i'm complete lost here.
how do i make it so that it makes sure that it checks all the way through the list first and not just the first one that it sees that fits the condition?
then how can you swap their value if the value of list[x] has already changed to list[i]?
- 10-28-2008, 03:14 AM #2
Senior Member
- Join Date
- Sep 2008
- Posts
- 564
- Rep Power
- 5
There is a Wikipedia article for this with pseudocode. It doesn't get much easier than that.
- 10-28-2008, 08:18 AM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
- 10-28-2008, 01:49 PM #4
To do a swap of contents of two variables you need a third variable to hold the value.list[x] = list[i];
list[i] = list[x];
The above will make the two array elements have the same content.
The first line copies [i] to [x] making them both the same, losing the original contents of [x]. You need to save [x] in a temp so you can put store it into [i] next. Take a piece of paper and do the steps one at a time to see.
- 10-28-2008, 02:02 PM #5
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Norm, is that clear what our OP is going to do? Trying to swap two consecutive numbers or else.
- 10-28-2008, 02:24 PM #6
Eranga,
I'm just guessing. The code looked like a common mistake when trying to swap two variables.
Without comments (Why don't teachers insist on coments???)
there is no way to know what the OP is trying to do.
- 10-28-2008, 02:33 PM #7
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Similar Threads
-
Return onyl 1 MX record if numerous exist
By rlzyoner in forum New To JavaReplies: 1Last Post: 08-05-2008, 11:41 PM -
List Selection
By Sarinam in forum AWT / SwingReplies: 2Last Post: 07-14-2008, 06:16 AM -
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 -
Code for selection
By kneekow in forum EclipseReplies: 0Last Post: 02-01-2008, 03:10 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks