-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBubbleSorting.java
More file actions
41 lines (40 loc) · 1.19 KB
/
Copy pathBubbleSorting.java
File metadata and controls
41 lines (40 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Scanner;
class BubbleSorting {
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
// Taking the length of array as input from user
System.out.println("Enter the size of the array:");
int len = scan.nextInt();
// Creating array of the entered length
int arr[] = new int[len];
// Taking array contents as input from user
System.out.println("Enter the array elements:");
for (int i = 0; i <= arr.length-1; i++) {
System.out.println("Enter an element:");
arr[i] = scan.nextInt();
}
// Printing the array contents before sorting
System.out.println("Array contents before sorting:");
for(int i = 0; i <= arr.length-1; i++) {
System.out.print(arr[i] + " ");
}
// Sorting the array contents in ascending order using bubble sort
int help;
for (int i = 0; i <= arr.length-2; i++) {
for (int j = 0; j <= arr.length-2-i; j++) {
if(arr[j] > arr[j+1]) {
help = arr[j];
arr[j] = arr[j+1];
arr[j+1] = help;
}
}
}
// Printing the sorted array contents
System.out.println();
System.out.println("Sorted array contents are:");
for(int i = 0; i <= arr.length-1; i++) {
System.out.print(arr[i] + " ");
}
}
}