By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,538 Members | 1,130 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,538 IT Pros & Developers. It's quick & easy.

my ascending sort algo got problem. can you please point it out ? thank you for reading

P: n/a

int i,j,val=4;
int arr[]={4,7,3,9};
int temp=-1;

int iptr=-1;
for(i=0; i<=val-2;i++)
{

iptr=i;
for(j=i+1;j<=val-1;j++)
{

if(arr[j]>arr[iptr])
if(i !=iptr) {temp=arr[i];
arr[i]=arr[iptr];
arr[iptr]=temp;

}

}


}

for(int z=0; z< 4; z++) System.out.println(arr[z]); // result should
be 3,4,7,9


Jul 17 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Wil -

You had it sort of right - here is the bubble sort corrected.

public static void main (String args[])
{
int i, j;
int numElement = 4;
int arr[]={4,7,3,9};
int temp=-1;

int iptr=-1;

// Print out the initial array.

for (int y=0; y<4; y++)
{
System.out.println(arr[y]);
}

// Start the sort. Repeat number of elements less 1 times.

for(i=0; i<numElement;i++)
{
for (j=0; j<numElement-1; j++)
{
if (arr[j] < arr[j+1])
{
temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}

}

for (int y=0; y<4; y++)
{
System.out.println(arr[y]);
}
}

As a note, watch which elements you are switching. To make the sort
ascending or descinding, switch the < or > in the main comparison.

Hope this helps,

Fred.

"wil smiths" <sm***@holly.wor.com> wrote in message
news:40**********@news.tm.net.my...

int i,j,val=4;
int arr[]={4,7,3,9};
int temp=-1;

int iptr=-1;
for(i=0; i<=val-2;i++)
{

iptr=i;
for(j=i+1;j<=val-1;j++)
{

if(arr[j]>arr[iptr])
if(i !=iptr) {temp=arr[i];
arr[i]=arr[iptr];
arr[iptr]=temp;

}

}


}

for(int z=0; z< 4; z++) System.out.println(arr[z]); // result should be 3,4,7,9


Jul 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.