-
May 25th, 2018, 04:14 PM
#1
sorting an array
Hi I ran into this practice problem and it states
Code:
Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees.
Example
For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].
so what i have is:
Code:
int[] sortByHeight(int[] a) {
for(int i=0; i<a.length; i++){ //goes through the array
if(a[i] != -1){ //if the values at index i does not equal -1 executes the following
int min = i; //going to compare the rest of the array with the value at this index
for(int j = i+1; j<a.length; j++){ //going through the array from the index above i
if(a[j] < a[i] && a[j] != -1) //if the value at index i+1 is less than the index at i and the value at index i+1 is not
//equal to -1
min = j; //then set the index of the smaller value to the min
}
int temp = a[min]; //swaps values
a[min] = a[i];
a[i] = temp;
}
}
return a;
}
im not sure why but this wont sort when a: [-1, 150, 190, 170, -1, -1, 160, 180]
i get a return of the same array.
im curious to know if anyone sees what im doing wrong.
for my first if statement isn't it supposed to for to the next index if the value is equal it -1?
Tags for this Thread
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
|
Click Here to Expand Forum to Full Width
|