+ 2
Write Solution to this program?
2 odpowiedzi
+ 3
With condition k<a.length; a[k+1] will be IndexOut of bounds error.
Use instead k<a.length-1
+ 1
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
int temp;
Scanner s = new Scanner(System.in);
System.out.println("Enter array size:");
int n = s.nextInt();
int[] a = new int[n];
System.out.println("Enter array values:");
for (int i = 0; i < a.length; i++) {
a[i] = s.nextInt();
}
// Bubble Sort
for (int j = 0; j < a.length - 1; j++) {
for (int k = 0; k < a.length - 1 - j; k++) {
if (a[k] > a[k + 1]) {
temp = a[k];
a[k] = a[k + 1];
a[k + 1] = temp;
}
}
}
System.out.println("Sorted array:");
for (int l = 0; l < a.length; l++) {
System.out.println(a[l]);
}
}
}