gpt4 book ai didi

java - 此选择排序代码有什么错误?错误:Arrayindexoutofboundsexception

转载 作者:行者123 更新时间:2023-12-02 04:28:39 26 4
gpt4 key购买 nike

我试图执行选择排序,使用不带临时变量的交换。我没有使用数组的正确方法。请帮忙。

import java.io.*;
import java.util.*;

class SelectionSort {
public static void main(String args[]) {
Scanner S=new Scanner(System.in);
int size,i,j;
System.out.println("How many elements");
size = S.nextInt();
int[] array = new int[size];
System.out.println("Type the element in unsorted order");
for (i=0; i<size; i++) {
array[i]=S.nextInt();
}
for (i=0; i<size; i++) {
for (j=i++; j<=size; j++) {
if(array[j]<array[i]) {
array[i]=array[i]+array[j];
array[j]=array[i]-array[j];
array[i]=array[i]-array[j];
}
}
}
System.out.println("Elements in sorted order:");
for(i=0; i<size; i++) {
System.out.println(array[i]);
}
}
}

最佳答案

参见以下代码:将for (j=i++; j<=size; j++)更改为for (j=i+1; j<size; j++)

import java.util.Scanner;

class SelectionSort {
public static void main(String args[]) {
Scanner S = new Scanner(System.in);
int size, i, j;
System.out.println("How many elements");
size = S.nextInt();
int array[] = new int[size];
System.out.println("Type the element in unsorted order");
for (i = 0; i < size; i++) {
array[i] = S.nextInt();
}
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++) {
if (array[j] < array[i]) {
array[i] = array[i] + array[j];
array[j] = array[i] - array[j];
array[i] = array[i] - array[j];
}
}
}
System.out.println("Elements in sorted order:");
for (i = 0; i < size; i++) {
System.out.println(array[i]);
}
}
}

关于java - 此选择排序代码有什么错误?错误:Arrayindexoutofboundsexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31823989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com