Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f42fc4b

Browse files
committed
Arrays & Heaps
1 parent a72dcbe commit f42fc4b

6 files changed

+2637
-59
lines changed

src/main/java/com/arrays/InversionCountInArray_MergeSort.html

Lines changed: 2475 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package com.arrays;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Inversion Count : For an array, inversion count indicates how far (or close) the array is from being sorted.
7+
* If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
8+
* Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
9+
* <p>
10+
* <p>
11+
* Algorithm:
12+
* The idea is similar to merge sort, divide the array into two equal or almost equal halves in each step until the base case is reached.
13+
* Create a function merge that counts the number of inversions when two halves of the array are merged,
14+
* create two indices i and j, i is the index for first half and j is an index of the second half.
15+
* if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] … a[mid]) will be greater than a[j].
16+
* Create a recursive function to divide the array into halves and find the answer by summing the number of inversions is the first half, number of inversion in the second half and the number of inversions by merging the two.
17+
* The base case of recursion is when there is only one element in the given half.
18+
* Print the answer
19+
* <p>
20+
* <p>
21+
* Complexity Analysis:
22+
* Time Complexity: O(n log n), The algorithm used is divide and conquer, So in each level one full array traversal is needed and there are log n levels so the time complexity is O(n log n).
23+
* Space Compelxity:O(1), No extra space is required.
24+
*/
25+
public class InversionCountInArray_MergeSort {
26+
27+
// Merge two sorted subarrays arr[low .. mid] and arr[mid + 1 .. high]
28+
public static int merge(int[] arr, int leftIndex, int midIndex, int rightIndex) {
29+
// Left subarray
30+
int[] left = Arrays.copyOfRange(arr, leftIndex, midIndex + 1);
31+
32+
// Right subarray
33+
int[] right = Arrays.copyOfRange(arr, midIndex + 1, rightIndex + 1);
34+
35+
int leftCursor = 0, rightCursor = 0, current = leftIndex, swaps = 0;
36+
37+
while (leftCursor < left.length && rightCursor < right.length) {
38+
if (left[leftCursor] <= right[rightCursor])
39+
arr[current++] = left[leftCursor++];
40+
else {
41+
arr[current++] = right[rightCursor++];
42+
swaps += (midIndex + 1) - (leftIndex + leftCursor); /**important*/
43+
}
44+
}
45+
46+
// Fill from the rest of the left subarray
47+
while (leftCursor < left.length)
48+
arr[current++] = left[leftCursor++];
49+
50+
// Fill from the rest of the right subarray
51+
while (rightCursor < right.length)
52+
arr[current++] = right[rightCursor++];
53+
54+
return swaps;
55+
}
56+
57+
// Sort array arr [low..high] using auxiliary array aux[]
58+
public static int mergeSort(int[] arr, int low, int high) {
59+
// Base case
60+
if (high == low) { // if run size == 1
61+
return 0;
62+
}
63+
64+
// find mid point
65+
int mid = (low + high) / 2;
66+
int inversionCount = 0;
67+
68+
// recursively split runs into two halves until run size == 1,
69+
// then merge them and return back up the call chain
70+
71+
inversionCount += mergeSort(arr, low, mid); // split / merge left half
72+
inversionCount += mergeSort(arr, mid + 1, high); // split / merge right half
73+
inversionCount += merge(arr, low, mid, high); // merge the two half runs
74+
75+
return inversionCount;
76+
}
77+
78+
public static void main(String[] args) {
79+
int[] arr = {1, 9, 6, 4, 5};
80+
int[] aux = Arrays.copyOf(arr, arr.length);
81+
82+
// get inversion count by performing merge sort on arr
83+
System.out.println("Inversion count is " +
84+
mergeSort(arr, 0, arr.length - 1));
85+
}
86+
}

src/main/java/com/arrays/SortArrayOf0s1s2s_DutchNationalFlagAlgo.java

Lines changed: 60 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.arrays;
22

3-
/*
4-
Dutch National Flag Algorithm, or 3-way Partitioning
3+
/**
4+
Dutch National Flag Algorithm, or 3-way Partitioning
55
66
Sort an array of 0s, 1s and 2s
77
Given an array A[] consisting 0s, 1s and 2s.
@@ -21,76 +21,81 @@
2121
Count the number of 0’s, 1’s and 2’s. After Counting, put all 0’s first, then 1’s and lastly 2’s in the array.
2222
We traverse the array two times. Time complexity will be O(n).
2323
24-
Best Solution
25-
https://algorithmsandme.com/dutch-national-flag-problem/
26-
*/
27-
28-
public class SortArrayOf0s1s2s_DutchNationalFlagAlgo {
29-
/*
3024
Dutch national flag problem : algorithm
3125
Start with three pointers : reader, low and high.
3226
reader and low are initialized as 0 and high is initialized as last element of array as size-1.
3327
reader will be used to scan the array while low and high will be used to swap elements to their desired positions.
3428
Starting with current position of reader, follow below steps, keep in mind we need 0 at start of array
3529
If element at index reader is 0, swap element at reader with element at low and increment low and reader by 1.
3630
If element at reader is 1, do not swap and increment reader by 1.
37-
If element at reader is 2, swap element at reader with element at high and decrease high by 1*/
31+
If element at reader is 2, swap element at reader with element at high and decrease high by 1
3832
33+
Actually, three pointers divide array into four parts. Red, white, unknown and Blue.
34+
Every element is taken from unknown part and put into its right place.
35+
So all three other parts expand while unknown part shrinks.
3936
40-
public void dutchNationalFlagAlgorithm(){
37+
Best Solution
38+
https://algorithmsandme.com/dutch-national-flag-problem/
39+
*/
4140

42-
}
4341

44-
public static void sort012(int arr[], int arr_size) {
45-
int countZero = 0;
46-
int countOne = 0;
47-
int countTwo = 0;
48-
for (int a : arr) {
49-
if (a == 0) {
50-
countZero++;
51-
} else if (a == 1) {
52-
countOne++;
53-
} else if (a == 2) {
54-
countTwo++;
55-
}
56-
}
42+
public class SortArrayOf0s1s2s_DutchNationalFlagAlgo {
5743

58-
int i = 0;
59-
while (countZero > 0) {
60-
arr[i] = 0;
61-
countZero--;
62-
i++;
44+
public static void swap(int[] input, int i, int j){
45+
int temp = input[i];
46+
input[i] = input[j];
47+
input[j] = temp;
6348
}
6449

65-
while (countOne > 0) {
66-
arr[i] = 1;
67-
countOne--;
68-
i++;
69-
}
50+
public static void dutchNationalFalgAlgorithm(int [] input){
51+
52+
//initialize all variables
53+
int reader = 0;
54+
int low = 0;
55+
int high = input.length - 1;
56+
57+
while(reader <= high){
58+
/*
59+
input always holds a permutation of the
60+
original data with input(0..(lo-1)) =0,
61+
input(lo..(reader-1))=1, input(reader..hi) is
62+
untouched, and input((hi+1)..(input.length-1)) = 2
63+
*/
64+
if(input[reader] == 0){
65+
/*When element at reader is 0, swap
66+
element at reader with element at index
67+
low and increment reader and low*/
68+
swap(input, reader, low);
69+
reader++;
70+
low++;
71+
}
72+
else if(input[reader] == 1){
73+
/* if element at reader is just
74+
increment reader by 1 */
75+
reader++;
76+
}
77+
else if(input[reader] == 2){
78+
/* If element at reader is 2, swap
79+
element at reader with element at
80+
high and decrease high by 1 */
81+
swap(input, reader, high);
82+
high--;
83+
}
84+
else{
85+
System.out.println("Bad input");
86+
break;
87+
}
88+
}
7089

71-
while (countTwo > 0) {
72-
arr[i] = 2;
73-
countTwo--;
74-
i++;
7590
}
91+
public static void main(String[] args) {
92+
int[] input = {2,2,1,1,0,0,0,1,1,2};
7693

77-
}
78-
94+
dutchNationalFalgAlgorithm(input);
7995

80-
/* Utility function to print array arr[] */
81-
static void printArray(int arr[], int arr_size) {
82-
int i;
83-
for (i = 0; i < arr_size; i++)
84-
System.out.print(arr[i] + " ");
85-
System.out.println("");
96+
for(int i=0; i<input.length; i++){
97+
System.out.print(" " + input[i]);
98+
}
99+
}
86100
}
87101

88-
/*Driver function to check for above functions*/
89-
public static void main(String[] args) {
90-
int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
91-
int arr_size = arr.length;
92-
sort012(arr, arr_size);
93-
System.out.println("Array after seggregation ");
94-
printArray(arr, arr_size);
95-
}
96-
}

src/main/java/com/arrays/TripletSumInArray_Sorting_TwoPointerAlgo.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ public class TripletSumInArray_Sorting_TwoPointerAlgo {
3333

3434
public static void find_all_triplets(int[] arr, int sum) {
3535

36-
// sort array elements
37-
Arrays.sort(arr); /*important*/
36+
/**sort array elements*/
37+
Arrays.sort(arr); /**important*/
3838

3939
int n = arr.length;
4040
int left;

src/main/java/com/heaps/KthLargestElement.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
import java.util.PriorityQueue;
44

5-
/*
5+
/**
66
77
Link to priority Queue -
8-
https://onedrive.live.com/redir?resid=26052E8C3C647484%21105&page=Edit&wd=target%28Queue.one%7C71d394a6-f4c4-41dd-b56a-e1878e78a88a%2FPriorityQueue%7C27bf58ff-75e1-4c3a-aa71-2823e1ff846b%2F%29
8+
https://onedrive.live.com/redir?resid=26052E8C3C647484%21105&page=Edit&wd=target%28Queue.one%7C71d394a6-f4c4-41dd-b56a-e1878e78a88a%2FPriorityQueue%7C27bf58ff-75e1-4c3a-aa71-2823e1ff846b%2F%29&wdorigin=703
99
1010
An Efficient Solution is to use Min Heap of size k to store k largest elements of the stream.
1111
The k’th largest element is always at root and can be found in O(1) time.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.test;
2+
3+
public class TestDefault {
4+
int i;
5+
6+
7+
public static void main (String args[]){
8+
TestDefault td = new TestDefault();
9+
System.out.println(td.i);
10+
11+
}
12+
}

0 commit comments

Comments
 (0)