As mentioned above, I tried to implement a bubble sort method but every time I try to run it, it returns ones and zeroes instead of the sorted numbers.
So far I've tried to look at another example of bubble sort from a complete and working program, but nothing seems to have worked. I'd really appreciate if you could help me come to a solution. The code below will include my entire program.
import java.util.*;
public class task2Q3
{
public static void main (String []args)
{
Scanner sc= new Scanner(System.in);
sc.useDelimiter("\n");
int [] myArr= new int[15];
int time= 0;
// This asks the user to imput the amount of time spent infront of a tablet
for(int i=0; i<myArr.length; i++)
{
System.out.println("Enter the amount of time you spend on the tablet daily" +i);
sc.nextInt();
myArr[i] ++;
}
bubbleSort(myArr);
for(int i=0; i<myArr.length; i++)
{
System.out.println(myArr[i]);
}
}
public static void bubbleSort(int[] tms)
{
boolean isSwapped= false;
do{
isSwapped= false;
for(int i=0; i<tms.length-1; i++)
{
if(tms[i]>tms[i+1])
{
int tmp= tms[i];
tms[i]= tms[i+1];
tms[i+1]= tmp;
}
}
}while(isSwapped== true);
}
}
I have notice 2 issues in your program
You are not storing input element in your array so replace these 2 lines
sc.nextInt();
myArr[i] ++;
//Replace above line with this
myArr[i] = sc.nextInt();
Add isSwapped = true
after swapping the elements
if(tms[i]>tms[i+1])
{
int tmp= tms[i];
tms[i]= tms[i+1];
tms[i+1]= tmp;
isSwapped = true;
}