DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. lindsey Guest

## sort numbers

OK, I'm trying to sort 5 random numbers. Here is my code. My logic is messed
up, so if you have any suggestions......

for(int hf = 0; hf < 5; hf++){
if (posOne > unsort[hf]){

tempPos = posOne;
posOne = unsort[hf];
unsort[n] = tempPos;

tempPos = unsort[0];
unsort[x] = tempPos;
unsort[0] = posOne;

n++;
x++;
}
}
Here is the output. As you can see it's not sorted.

14 18 4 9 14 unsorted
4 18 4 9 14 sorted

2. Faisal Guest

## Re: sort numbers

Try this

for (int i=0;i<n-1;i++ )
{
for (int j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
Faisal

"lindsey" <zave4@aol.com> wrote:
>
>OK, I'm trying to sort 5 random numbers. Here is my code. My logic is

messed
>up, so if you have any suggestions......
>
> for(int hf = 0; hf < 5; hf++){
> if (posOne > unsort[hf]){
>
> tempPos = posOne;
> posOne = unsort[hf];
> unsort[n] = tempPos;
>
> tempPos = unsort[0];
> unsort[x] = tempPos;
> unsort[0] = posOne;
>
> n++;
> x++;
> }
> }
>Here is the output. As you can see it's not sorted.
>
> 14 18 4 9 14 unsorted
> 4 18 4 9 14 sorted
>

3. Ruchi Dhar Guest

## Re: sort numbers

JDK1.2 has sor algorithms inbuilt in the utils.

Use java.util.Arrays.sort(int[]) to sort your int array. It uses Quicksort
algorithm which is lots better than the bubble sort.

"lindsey" <zave4@aol.com> wrote:
>
>OK, I'm trying to sort 5 random numbers. Here is my code. My logic is

messed
>up, so if you have any suggestions......
>
> for(int hf = 0; hf < 5; hf++){
> if (posOne > unsort[hf]){
>
> tempPos = posOne;
> posOne = unsort[hf];
> unsort[n] = tempPos;
>
> tempPos = unsort[0];
> unsort[x] = tempPos;
> unsort[0] = posOne;
>
> n++;
> x++;
> }
> }
>Here is the output. As you can see it's not sorted.
>
> 14 18 4 9 14 unsorted
> 4 18 4 9 14 sorted
>

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise