-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubble_Sort.java
More file actions
66 lines (45 loc) · 1.3 KB
/
Bubble_Sort.java
File metadata and controls
66 lines (45 loc) · 1.3 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*Bubble Sort is the simplest sorting algorithm
* that works by repeatedly swapping the adjacent elements
* if they are in wrong order.
*
* O(n2)*/
package java_ds_algo;
import java.util.Scanner;
public class Bubble_Sort {
public static int[] bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
return arr;
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter length of array");
int n = sc.nextInt();
int[] arr = new int[n];//array
System.out.println("Enter Elements to be sorted");
for(int i = 0;i < n;i++) {
arr[i] = sc.nextInt();
}
if(arr.length == 1) {
System.out.print("No need for sorting");
}
int ans[] = bubbleSort(arr);
printArray(ans);
}
}