I have been confronting with a very confusing situation, I wrote this BubbleSort program and it ran just fine. with the correct output:
public class BubbleSortInput {
private static void Sorting(int[] intArray)
{
int i, temp=0;
int n = intArray.length;
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < n-i-1; j++)
{
if(intArray[i]>intArray[i+1])
{
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
}
}
}
}
public static void main(String[] args) {
int array[] = {1,5,65,34,76,234};
Sorting(array);
for(int k = 0; k < array.length; k++)
{
System.out.println(array[k]);
}
}
}
However, I tried to write basically the same code, in the main method, in another class:
class BubbleSort {
public static void main(String[] args) {
int numbers[] = {12,43,65,12,65,92,32,54};
int i,temp=0;
for(i=0; i < numbers.length-1; i++)
{
for(int j = 0; j < numbers.length-i-1; j++)
{
if(numbers[i]>numbers[i+1])
{
temp = numbers[i+1];
numbers[i] = numbers[i+1];
numbers[i]= temp;
}
}
}
for(i=0;i<numbers.length;i++)
{
System.out.println(numbers[i]);
}
}
}
The output I get on the second file is completely wrong, even though I used almost the same code, Can someone explain this please?
Output:
12
43
12
12
65
32
32
54