Trying to code so that a list of numbers that the user inputs is sorted through bubble sorting. This is what I have so far:
import java.util.Scanner;
public class BubbleSort
{
public static void main(String[] args)
{
int n;
int[] list[];
System.out.println("Please enter number of the elements to be sorted");
Scanner keyboard = new Scanner(System.in);
n = keyboard.nextInt();
for ( int pass = 1; pass < n; pass++)
for (int i = 0; i < n - pass ; i++)
{
if (list[i] > list[i + 1]){
int temp = list[n];
list[i] = list[i + 1];
list[i + 1] = temp;
}
}
}
}
I get the following error that says
The operator > is undefined for the argument type(s) int[], int[]" for the line: if (list[i] > list[i + 1])
type mismatch: cannot convert from int[] to int" for line: int temp = list[n];
Type mismatch: cannot convert from int to int[]" for line: list[i + 1] = temp;
Thank you so much in advance for your time and help.
You just declared a 2D
array using this int[] list[];
. 2D array is an array of arrays and can be declared like this
int list[][];
int []list[];
int[] list[];
but your requirement is of 1D array which should be declared like this
int[] list;
int list[];
plus you forgot the initialization of your array and taking array data values from user, To initiliaze array
n = keyboard.nextInt();
list=new int[n]; // initialize array length
To take array value from user , you need to again loop n
times and take input using keyboard.nextInt();
to take all array values
see this example to properly implement your logic
package com.borntoinnovation.datastructure;
import java.util.Arrays;
//Sort between value like 0-1, 1-2, 2-3, 3-4, 4-5 :Suppose end is 5
//0-1, 1-2, 2-3, 3-4 ( 5th already sorted into their position
//0-1, 1-2, 2-3 (4th sorted)
//.... like that
public class SortingBubble {
public static void main(String[] args) {
int[] array = new int[] { 40, 10, -30, 45, 39, 32 };
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] < array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
System.out.println(Arrays.toString(array));
}
}
}
/*
* [40, 10, 45, 39, 32, -30]
* [40, 45, 39, 32, 10, -30]
* [45, 40, 39, 32, 10, -30]
*/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.