12th Jun 2023, 3:11 PM
KGS Sumanth
KGS Sumanth - avatar
2 Antworten
+ 3
With condition k<a.length; a[k+1] will be IndexOut of bounds error. Use instead k<a.length-1
12th Jun 2023, 3:22 PM
Jayakrishna 🇮🇳
+ 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]); } } }
14th Jun 2023, 11:05 AM
Vaibhav
Vaibhav - avatar