-
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
-
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
>
-
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
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks