help in sorting the array

i'm trying to sort this array in special method by :

- Counting the number of smaller elements to find the correct position i.

– If the element is in its correct position, move to the succeeding element.

– Otherwise, swap the current element with the one found in position i.

– Repeat the previous steps till you reach the last element.

So i did this code but something wrong so please help :

public class Ass {

public static void swap(int [] x) {

int i = 0 ;

while (i<x.length){

for (int j = 0 ; j<x.length ; j++){

int b = 0 ;

if ( x[i] > x[j] ) {

b++ ;

}

if (b!=0) {

int tmp = x[i] ;

x[i]=x[b] ;

x[b]= tmp ;

}

}

i++ ;

}

}

public static void main (String [] args) {

int [] array = {5,7,3,6,9} ;

swap(array) ;

for (int k = 0 ; k<array.length ; k++)

System.out.print(array[k] + " ");

}

}

Re: help in sorting the array

Please use code tags as described in the announcements page as well as in your previous thread.

Re: help in sorting the array

Hi,

I checked your code, even executed the same and what I found was,

a change is needed in the swap code.

what you have written is :

Code Java:

int tmp = x[i] ;
x[i]=x[b] ;
x[b]= tmp ;

which should be as follows :

Code Java:

int tmp = x[i] ;
x[i]=x[j] ;
x[j]= tmp ;

Because, since you are comparing the values at i and j positions, and if you find value at i is greater than value at j, then you should swap the values at **i and j** only but right now you are performing the swap between the values at** i and b,** which is wrong.

b is just like a check variable ,to find out whether the value at ' i greater than j ' condition is true or false.

actually there is no need of the variable b. you can compare the values and directly swap like below :

Code Java:

if (x[i] > x[j]) {
int tmp = x[i];
x[i] = x[j];
x[j] = tmp;
}

Re: help in sorting the array

thnkxxx so muchh :) :) but this prints the biggest first i want the smallest , any help ??

Re: help in sorting the array

nvmmm i solved it thnkxxx :)

Re: help in sorting the array

@ind

Please see The problem with spoonfeeding.

Since the OP has already taken the code provided and run with it, I am not going to delete it, but please see the link and try to be more suggestive and a little less free answers in your posts.