I'm having trouble manually sorting the array with a for loop. It works except for the first and last number. Here's my code:
Scanner numInput = new Scanner(System.in);
int tempVar, num;
String numbersString;
int[] numbers = {4, 11, 13, 12, 17, 35, 15, 7, 19, 3, 45};
for (int i = 0; i < numbers.length - 1; i++)
{
for(int j = 0; j < numbers.length - 1; j++)
{
if(numbers[i] < numbers[j + 1])
{
tempVar = numbers [j + 1];
numbers [j + 1]= numbers [i];
numbers [i] = tempVar;
}
}
}
numbersString = Arrays.toString(numbers);
System.out.println(numbersString);
You have to initialize the value for j as i+1, this sorting algorithm is called bubble sort, that works by repeatedly swapping the adjacent elements if they are in wrong order. The below method is always runs O(n^2) time even if the array is sorted.
public static void main (String[] args)
{
int[] array = {4,2,1,3,5,9,6,8,7};
for(int i = 0 ; i < array.length;i++)
{
for(int j = i+1 ; j< array.length;j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With