I have a simple algorithm to order numbers in an array, all of the elements become ordered except for the last one. I have tried changing the bounds of my loops to fix this, but it just creates an infinite loop instead.
1 Answer
while (pointer < arrayLength){
int min = findMinFrom(pointer);
for (int i = pointer; i < arrayLength; i ++){
if (A[i] == min){
swap(i, pointer);
pointer ++;
}
compNewS ++;
}
}
You see what's the problem? Your pointer will be updated only if A[i] == min if not then it will keep looping. Put your pointer++ out of that condition.
This can be done with only two loops but here is an adjusted version of your code:
public class Numbers {
private static int [] A ;
public static void main(String [] args) {
int [] array = {3,2,1,4,5,6,7,8,9,7};
A = array;
newSort(array, array.length);
for(int i = 0; i < A.length;i++)
System.out.println(A[i]);
}
public static void newSort(int[] array, int arrayLength){
int pointer = 0;
int p = 0;
while(p < array.length) {
int min = findMinFrom(p,array);
int temp = array[p];
array[p] = min;
array[min] = temp;
p++;
}
}
public static int findMinFrom(int p, int[] array){
int min = p;
for (int i = p; i < array.length; i ++){
if (A[i] < array[p]){
min =i;
}
}
return min;
}
}
6 Comments
W.Howe
The pointer is supposed to be inside the if loop, moving it outside doesn't fiz the error
ttzn
Moving out the
pointer++ instruction makes the program terminate, but it also makes it incorrect.Luai Ghunim
It will fix the error and your implementation is totally wrong. Can you tell me how many elemnts you have same in on array? in a array of 10 elements if 5 are equal to min then pointer will never reach array.length and loop will never break;
Luai Ghunim
SelectionSort finds minimum from whole list then swaps it with first element and then finds again minimum for 2 to n and swaps it with second element and so forth.
W.Howe
There are 5 elements in the array, all of the elements are different numbers
|
array.lengthand notarray.length-1for(int i = pointer+1; i <A.length; i++)btw your swap method is also not correct.swapandgetUsedSizefunctions, along with the type declaration of thatAarray.