Skip to content

Commit 63bcf42

Browse files
piyush072Phantsure
authored andcommitted
Sorting Algorithm implemented in Java (Phantsure#10)
1 parent c10c64a commit 63bcf42

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class BubbleSort
2+
{
3+
void bubbleSort(int arr[])
4+
{
5+
int n = arr.length;
6+
for (int i = 0; i < n-1; i++)
7+
for (int j = 0; j < n-i-1; j++)
8+
if (arr[j] > arr[j+1])
9+
{
10+
// swap temp and arr[i]
11+
int temp = arr[j];
12+
arr[j] = arr[j+1];
13+
arr[j+1] = temp;
14+
}
15+
}
16+
17+
void printArray(int arr[])
18+
{
19+
int n = arr.length;
20+
for (int i=0; i<n; ++i)
21+
System.out.print(arr[i] + " ");
22+
System.out.println();
23+
}
24+
public static void main(String args[])
25+
{
26+
BubbleSort ob = new BubbleSort();
27+
int arr[] = {64, 34, 25, 12, 22, 11, 90};
28+
ob.bubbleSort(arr);
29+
System.out.println("Sorted array");
30+
ob.printArray(arr);
31+
}
32+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class InsertionSort {
2+
/*Function to sort array using insertion sort*/
3+
void sort(int arr[])
4+
{
5+
int n = arr.length;
6+
for (int i = 1; i < n; ++i) {
7+
int key = arr[i];
8+
int j = i - 1;
9+
10+
/* Move elements of arr[0..i-1], that are
11+
greater than key, to one position ahead
12+
of their current position */
13+
while (j >= 0 && arr[j] > key) {
14+
arr[j + 1] = arr[j];
15+
j = j - 1;
16+
}
17+
arr[j + 1] = key;
18+
}
19+
}
20+
21+
/* A utility function to print array of size n*/
22+
static void printArray(int arr[])
23+
{
24+
int n = arr.length;
25+
for (int i = 0; i < n; ++i)
26+
System.out.print(arr[i] + " ");
27+
28+
System.out.println();
29+
}
30+
31+
// Driver method
32+
public static void main(String args[])
33+
{
34+
int arr[] = { 12, 11, 13, 5, 6 };
35+
36+
InsertionSort ob = new InsertionSort();
37+
ob.sort(arr);
38+
39+
printArray(arr);
40+
}
41+
}

0 commit comments

Comments
 (0)