Can someone help me with my homework? my teacher asked us to create a program that lets the user to input 5 integers and sort it using bubblesort. i have already write the code but its not the output that i expected. heres the code:

import java.util.Scanner;
public class bubble {

	static final int arraySize=5;
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);

		int[] list=new int[arraySize];
		int i,x;
		bubbleSort(list,arraySize);


		for(x=0;x<arraySize;x++){
			System.out.print("Enter a number: ");
			list[x]=scan.nextInt();
		}

		System.out.println("After sorting, the list elements are:");

		for(i=0;i<arraySize;i++){
			System.out.print(list[i]+" ");
		}
		System.out.println();

	}
		public static void bubbleSort(int list[], int listLength)
		{
			int temp;
			int counter,index;

			for(counter=0;counter<listLength-1;counter++)
			{
				for(index=0;index<listLength-1-counter;index++)
					if(list[index]>list[index+1])
					{
						temp=list[index];
						list[index]=list[index+1];
						list[index+1]=temp;
					}
			}
		}
}

for example i inputted numbers: 5,4,3,1,2
the output is still the same numbers that i inputted. what seems to be the problem. please help :(

Recommended Answers

All 2 Replies

Member Avatar for ztini

The problem is your 2nd nested loop; the index should start at length - 1, while it is > counter, and decrementing.

So your program might look something like this:

import java.util.Scanner;


public class BubbleSort {

	private int[] list = new int[5];
	
	public BubbleSort() {
		getInput();
		sort();
		print();
	}
	
	private void getInput() {
		Scanner in = new Scanner(System.in);
		for (int i = 0; i < list.length; i++) {
			System.out.print("Input: ");
			list[i] = in.nextInt();
		}
	}
	
	private void sort() {
		for (int i = 0; i < list.length; i++) {
			for (int j = list.length - 1; j > i; j--) {
				if (list[j - 1] > list[j]) {
					int temp = list[j];
					list[j] = list[j - 1];
					list[j - 1] = temp;
				}
			}
		}
	}
	
	private void print() {
		System.out.print("Sorted: ");
		for (int i : list) {
			System.out.print(i + " ");
		}
	}
	
	public static void main(String[] args) {
		new BubbleSort();
	}
}

thank you sir for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.