如上所述,我尝试实现冒泡排序方法,但每次我尝试运行它时,它都会返回 1 和 0,而不是排序后的数字。
到目前为止,我已经尝试从完整且有效的程序中查看另一个冒泡排序的示例,但似乎没有任何效果。如果您能帮助我找到解决方案,我将不胜感激。下面的代码将包含我的整个程序。
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);
}
}
您没有将输入的值分配给要求用户输入的
for
循环中的数组。相反,您可以调用 nextInt
而不存储输入。
这是程序的改进版本,它修复了此问题并提高了可读性:
import java.util.Arrays;
import java.util.Scanner;
import java.util.InputMismatchException;
public class Task2Q3 {
private static final int NUM_ENTRIES = 15;
public static void main(String[] args) {
int[] usageTimes = getUserInput();
bubbleSort(usageTimes);
System.out.printf("Sorted times %s%n", Arrays.toString(usageTimes));
}
private static int[] getUserInput() {
Scanner scanner = new Scanner(System.in);
int[] times = new int[NUM_ENTRIES];
System.out.println("Enter the amount of time you spend on the tablet daily:");
for (int i = 0; i < times.length; i++) {
times[i] = getIntInput(scanner, i + 1);
}
return times;
}
private static int getIntInput(Scanner scanner, int day) {
while (true) {
System.out.printf("Day %d: ", day);
try {
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter an integer.");
scanner.next();
}
}
}
private static void bubbleSort(int[] array) {
for (int end = array.length - 1; end > 0; end--) {
boolean isSwapped = false;
for (int i = 0; i < end; i++) {
if (array[i] > array[i + 1]) {
swap(array, i, i + 1);
isSwapped = true;
}
}
if (!isSwapped) break;
}
}
private static void swap(int[] array, int firstIndex, int secondIndex) {
int temp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
}
}
我注意到您的程序中有 2 个问题
您没有将输入元素存储在数组中,因此请替换这两行
sc.nextInt();
myArr[i] ++;
//Replace above line with this
myArr[i] = sc.nextInt();
交换元素后添加
isSwapped = true
if(tms[i]>tms[i+1])
{
int tmp= tms[i];
tms[i]= tms[i+1];
tms[i+1]= tmp;
isSwapped = true;
}