Sorting PDF
Sorting PDF
9 Alternative Sorting 66
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
1
Contents
14 Bitonic Sort 90
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
2
Contents
36 Check if a grid can become row-wise and column-wise sorted after ad-
jacent swaps 189
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
37 Check if a queue can be sorted into another queue using a stack 192
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
39 Check if any two intervals overlap among a given set of intervals 203
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
41 Check if both halves of the string have at least one different character 223
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
42 Check if given array is almost sorted (elements are at-most one position
away) 236
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
3
Contents
51 Check whether an array can be fit into another array rearranging the
elements in the array 290
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
4
Contents
67 Count number of triplets in an array having sum in the range [a, b] 409
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
68 Count number of triplets with product equal to given number Set 2 424
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
70 Count pairs from two linked lists whose sum is equal to a given value 435
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
71 Count pairs from two sorted arrays whose sum is equal to a given value x448
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
72 Count pairs from two sorted matrices with given sum 468
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
75 Count quadruples from four sorted arrays whose sum is equal to a given
value x 507
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
5
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
83 Efficiently merging two sorted arrays with O(1) extra space 569
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
86 Equally divide into two sets such that one set has maximum distinct
elements 598
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
88 Find Sum of all unique sub-array sum for a given array. 611
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
90 Find a pair of elements swapping which makes sum of two arrays same 624
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
6
Contents
96 Find all elements in array which have at-least two greater elements 690
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
101 Find four elements that sum to a given value Set 2 ( O(n^2Logn)
Solution) 728
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732
102 Find if k bookings possible with given arrival and departure times 733
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735
105 Find maximum height pyramid from the given array of objects 744
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
109 Find number of pairs (x, y) in an array such that x^y > y^x 773
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 780
110 Find number of pairs in an array such that their XOR is 0 781
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
112 Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting) 797
7
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
114 Find the Minimum length Unsorted Subarray, sorting which makes the
complete array sorted 806
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
116 Find the largest multiple of 3 from array of digits Set 2 (In O(n) time
and O(1) space) 819
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
117 Find the largest number that can be formed with the given digits 824
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
118 Find the minimum and maximum amount to buy all N candies 834
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841
120 Find whether an array is subset of another array Added Method 3 853
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869
121 Find whether it is possible to make array elements same using one
external number 870
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 872
124 Given a sorted array and a number x, find the pair in array whose sum
is closest to x 893
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900
125 Given a sorted dictionary of an alien language, find order of characters 901
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 907
127 Heap Sort for decreasing order using min heap 915
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920
8
Contents
131 How to make Mergesort to perform O(n) comparisons in best case? 950
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
138 Insertion sort to sort even and odd positioned elements in different
orders 997
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1001
9
Contents
156 K-th smallest element after removing some integers from natural num-
bers 1082
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1084
157 Know Your Sorting Algorithm Set 1 (Sorting Weapons used by Pro-
gramming Languages) 1085
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1087
158 Know Your Sorting Algorithm Set 2 (Introsort- C++’s Sorting Weapon) 1088
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1093
10
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1110
167 Maximise the number of toys that can be purchased with amount K 1130
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1135
173 Maximum area rectangle by picking four sides from array 1160
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1166
174 Maximum array from two given arrays keeping order same 1167
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1169
177 Maximum in an array that can make another array sorted 1177
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1179
11
Contents
183 Maximum sum of pairwise product in an array with negative allowed 1226
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1232
193 Merge Sort with O(1) extra space merge and O(n lg n) time 1305
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1309
12
Contents
196 Merge two sorted arrays with O(1) extra space 1323
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1328
199 Minimize the sum of product of two arrays with permutations allowed1347
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1352
203 Minimum difference between max and min of all K-size subsets 1370
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1376
209 Minimum partitions of maximum size 2 and sum limited by given value 1411
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1415
13
Contents
214 Minimum sum of two numbers formed from digits of an array 1441
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1446
215 Minimum swap required to convert binary tree to binary search tree 1447
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1448
219 Minimum swaps to reach permuted array with at most 2 positions left
swaps allowed 1463
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1466
223 No of pairs (a[j] >= a[i]) with k numbers in range (a[i], a[j]) that are
divisible by x 1484
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1486
224 Noble integers in an array (count of greater elements is equal to value) 1487
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1495
226 Number of paths from source to destination in a directed acyclic graph 1502
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1505
227 Number of sextuplets (or six values) that satisfy an equation 1506
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1508
14
Contents
228 Number of swaps to sort when only adjacent swapping allowed 1509
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1516
229 Number of visible boxes after putting one inside another 1517
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1521
231 PHP Sort array of strings in natural and standard orders 1529
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1530
232 Pair formation such that maximum pair sum is minimized 1531
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1533
237 Permute two arrays such that sum of every pair is greater or equal to K 1564
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1569
243 Print Binary Tree levels in sorted order Set 2 (Using set) 1603
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1605
244 Print all the pairs that contains the positive and negative values of an
element 1606
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1610
15
Contents
246 Print array of strings in sorted order without copying one string into
another 1623
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1625
247 Print n smallest elements from given array in their original order 1626
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1628
251 Printing frequency of each character just after its consecutive occurrences 1643
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1646
256 Python Code for time Complexity plot of Heap Sort 1669
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1671
16
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1682
266 Python Sort a List according to the Length of the Elements 1692
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1693
267 Python Sort a list according to the second element in sublist 1694
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1696
272 QuickSort Tail Call Optimization (Reducing worst case space to Log n 1723 )
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1725
17
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1769
280 Rearrange an array in maximum minimum form Set 2 (O(1) extra space) 1777
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1787
283 Rearrange array such that even positioned are greater than odd 1798
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1803
284 Rearrange positive and negative numbers using inbuilt sort function 1804
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1806
285 Rearrange positive and negative numbers with constant extra space 1807
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1820
289 Recursive selection sort for singly linked list Swapping node links 1839
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1843
18
Contents
299 Sleep Sort – The King of Laziness / Sorting while Sleeping 1914
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1919
301 Smallest Difference pair of values between two unsorted Arrays 1931
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1939
302 Smallest element in an array that is repeated exactly ‘k’ times. 1940
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1953
304 Smallest subset with sum greater than all other elements 1961
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1965
306 Sort 3 Integers without using if condition or using only max() function1974
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1978
19
Contents
313 Sort a linked list that is sorted alternating ascending and descending
orders? 2009
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2018
317 Sort all even numbers in ascending order and then sort all odd numbers
in descending order 2035
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2044
318 Sort an almost sorted array where only two elements are swapped 2045
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2048
319 Sort an array according to absolute difference with a given value “using
constant extra space” 2049
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2051
320 Sort an array according to absolute difference with given value 2052
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2054
322 Sort an array according to the order defined by another array 2065
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2076
20
Contents
333 Sort an array with swapping only with a special element is allowed 2134
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2137
337 Sort elements by frequency Set 4 (Efficient approach using hash) 2156
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2158
340 Sort first half in ascending and second half in descending order 1 2169
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2175
341 Sort first half in ascending and second half in descending order Set 2 2176
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2179
342 Sort first k values in ascending order and remaining n-k values in
descending order 2180
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2186
21
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2199
351 Sort the linked list in the order of elements appearing in the array 2227
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2230
354 Sorting 2D Vector in C++ Set 2 (In descending order by row and
column) 2244
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2247
360 Sorting Vector of Pairs in C++ Set 1 (Sort by first and second) 2262
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2266
22
Contents
364 Sorting an array according to another array using pair in STL 2284
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2286
367 Sorting array of strings (or words) using Trie Set-2 (Handling Duplicates) 2296
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2302
23
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2352
384 Sum of all elements between k1’th and k2’th smallest elements 2396
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2400
386 Tag Sort (To get both sorted and original) 2408
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2412
389 Time complexity of insertion sort when there are O(n) inversions? 2419
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2420
393 Union and Intersection of two linked lists Set-2 (Using Merge Sort) 2446
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2452
394 Union and Intersection of two linked lists Set-3 (Hashing) 2453
24
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2457
396 Ways to sort list of dictionaries by values in Python – Using itemgetter 2461
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2462
399 Which sorting algorithm makes minimum number of memory writes? 2465
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2465
400 Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists? 2466
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2467
401 Why is it faster to process sorted array than an unsorted array ? 2468
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2470
403 k largest(or smallest) elements in an array added Min Heap method 2473
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2476
404 k smallest elements in same order using O(1) extra space 2477
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2484
Contents
25
Chapter 1
26
Chapter 1. 3-Way QuickSort (Dutch National Flag)
int p = l-1, q = r;
int v = a[r];
while (true)
{
// From left, find the first element greater than
// or equal to v. This loop will definitely terminate
// as v is last element
while (a[++i] < v);
// From right, find the first element smaller than or
// equal to v
while (v < a[--j])
if (j == l)
break;
// If i and j cross, then we are done
if (i >= j) break;
// Swap, so that smaller goes on left greater goes on right
swap(a[i], a[j]);
// Move all same left occurrence of pivot to beginning of
// array and keep count using p
if (a[i] == v)
{
p++;
swap(a[p], a[i]);
}
// Move all same right occurrence of pivot to end of array
// and keep count using q
if (a[j] == v)
{
q--;
swap(a[j], a[q]);
}
}
// Move pivot element to its correct index
swap(a[i], a[r]);
// Move all left same occurrences from beginning
// to adjacent to arr[i]
j = i-1;
for (int k = l; k < p; k++, j--)
swap(a[k], a[j]);
27
Chapter 1. 3-Way QuickSort (Dutch National Flag)
Output:
4 9 4 4 1 9 4 4 9 4 4 1 4
1 1 4 4 4 4 4 4 4 4 9 9 9
28
Chapter 1. 3-Way QuickSort (Dutch National Flag)
29
Chapter 1. 3-Way QuickSort (Dutch National Flag)
//update i and j
i = low-1;
j = mid; //or high-1
}
// 3-way partition based quick sort
void quicksort(int a[], int low, int high)
{
if (low>=high) //1 or 0 elements
return;
int i, j;
// Note that i and j are passed as reference
partition(a, low, high, i, j);
// Recur two halves
quicksort(a, low, i);
quicksort(a, j, high);
}
// Driver program
int main()
{
int a[] = {4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4};
//int a[] = {4, 39, 54, 14, 31, 89, 44, 34, 59, 64, 64, 11, 41};
//int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//int a[] = {91, 82, 73, 64, 55, 46, 37, 28, 19, 10};
//int a[] = {4, 9, 4, 4, 9, 1, 1, 1};
int size = sizeof(a) / sizeof(int);
printarr(a, size);
quicksort(a, 0, size - 1);
printarr(a, size);
return 0;
}
Output:
4 9 4 4 1 9 4 4 9 4 4 1 4
1 1 4 4 4 4 4 4 4 4 9 9 9
30
Chapter 1. 3-Way QuickSort (Dutch National Flag)
Source
https://www.geeksforgeeks.org/3-way-quicksort-dutch-national-flag/
31
Chapter 2
Examples:
32
Chapter 2. 3-way Merge Sort
// copying alements of given array into
// duplicate array
for (int i = 0; i < fArray.length; i++)
fArray[i] = gArray[i];
// sort function
mergeSort3WayRec(fArray, 0, gArray.length, gArray);
// copy back elements of duplicate array
// to given array
for (int i = 0; i < fArray.length; i++)
gArray[i] = fArray[i];
}
/* Performing the merge sort algorithm on the
given array of values in the rangeof indices
[low, high). low is minimum index, high is
maximum index (exclusive) */
public static void mergeSort3WayRec(Integer[] gArray,
int low, int high, Integer[] destArray)
{
// If array size is 1 then do nothing
if (high - low < 2)
return;
// Splitting array into 3 parts
int mid1 = low + ((high - low) / 3);
int mid2 = low + 2 * ((high - low) / 3) + 1;
// Sorting 3 arrays recursively
mergeSort3WayRec(destArray, low, mid1, gArray);
mergeSort3WayRec(destArray, mid1, mid2, gArray);
mergeSort3WayRec(destArray, mid2, high, gArray);
// Merging the sorted arrays
merge(destArray, low, mid1, mid2, high, gArray);
}
/* Merge the sorted ranges [low, mid1), [mid1,
mid2) and [mid2, high) mid1 is first midpoint
index in overall range to merge mid2 is second
midpoint index in overall range to merge*/
public static void merge(Integer[] gArray, int low,
int mid1, int mid2, int high,
Integer[] destArray)
{
int i = low, j = mid1, k = mid2, l = low;
33
Chapter 2. 3-way Merge Sort
// choose smaller of the smallest in the three ranges
while ((i < mid1) && (j < mid2) && (k < high))
{
if (gArray[i].compareTo(gArray[j]) < 0)
{
if (gArray[i].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[i++];
else
destArray[l++] = gArray[k++];
}
else
{
if (gArray[j].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[j++];
else
destArray[l++] = gArray[k++];
}
}
// case where first and second ranges have
// remaining values
while ((i < mid1) && (j < mid2))
{
if (gArray[i].compareTo(gArray[j]) < 0)
destArray[l++] = gArray[i++];
else
destArray[l++] = gArray[j++];
}
// case where second and third ranges have
// remaining values
while ((j < mid2) && (k < high))
{
if (gArray[j].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[j++];
else
destArray[l++] = gArray[k++];
}
// case where first and third ranges have
// remaining values
while ((i < mid1) && (k < high))
{
if (gArray[i].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[i++];
34
Chapter 2. 3-way Merge Sort
else
destArray[l++] = gArray[k++];
}
// copy remaining values from the first range
while (i < mid1)
destArray[l++] = gArray[i++];
// copy remaining values from the second range
while (j < mid2)
destArray[l++] = gArray[j++];
// copy remaining values from the third range
while (k < high)
destArray[l++] = gArray[k++];
}
// Driver function
public static void main(String args[])
{
// test case of values
Integer[] data = new Integer[] {45, -2, -45, 78,
30, -42, 10, 19, 73, 93};
mergeSort3Way(data);
System.out.println("After 3 way merge sort: ");
for (int i = 0; i < data.length; i++)
System.out.print(data[i] + " ");
}
}
Output:
Here, we first copy the contents of data array to another array called fArray. Then, sort
the array by finding midpoints that divide the array into 3 parts and called sort function on
each array respectively. The base case of recursion is when size of array is 1 and it returns
from the function. Then merging of arrays starts and finally the sorted array will be in
fArray which is copied back to gArray.
Time Complexity: In case of 2-way Merge sort we get the equation: T(n) = 2T(n/2) +
O(n)
Similarly, in case of 3-way Merge sort we get the equation: T(n) = 3T(n/3) + O(n)
By solving it using Master method, we get its complexity as O(n log 3 n).. Although time
complexity looks less compared to 2 way merge sort, the time taken actually may become
35
Chapter 2. 3-way Merge Sort
higher because number of comparisons in merge function go higher. Please refer Why is
Binary Search preferred over Ternary Search? for details.
Similar article :
3 way Quick Sort
Source
https://www.geeksforgeeks.org/3-way-merge-sort/
36
Chapter 3
37
Chapter 3. 8086 program for selection sort
Algorithm –
Program –
Explanation – Registers AH, AL, BX, CX, DL, SI, DI are used for general purpose:
38
Chapter 3. 8086 program for selection sort
SI - Pointer
DI - Pointer
3. XOR CH, CH: stores the result of logical operation XOR b/w CH and CH in CH.
4. INC SI: increase the value of SI by 1.
5. DEC CX: decrease the value of CX by 1.
Source
https://www.geeksforgeeks.org/8086-program-selection-sort/
39
Chapter 4
Imagine a hypothetical machine where flip(i) always takes O(1) time. Write
an efficient program for sorting a given array in O(nLogn) time on the given
machine. If we apply the same algorithm here, the time taken will be O(n^2) because
the algorithm calls findMax() in a loop and find findMax() takes O(n) time even on this
hypothetical machine.
We can use insertion sort that uses binary search. The idea is to run a loop from second
element to last element (from i = 1 to n-1), and one by one insert arr[i] in arr[0..i-1] (like
standard insertion sort algorithm). When we insert an element arr[i], we can use binary
search to find position of arr[i] in O(Logi) time. Once we have the position, we can use some
flip operations to put arr[i] at its new place. Following are abstract steps.
40
Chapter 4. A Pancake Sorting Problem
Since flip operation takes O(1) on given hypothetical machine, total running time of above
algorithm is O(nlogn). Thanks to Kumar for suggesting above problem and algorithm.
Let us see how does the above algorithm work. ceilSearch() actually returns the index of
the smallest element which is greater than arr[i] in arr[0..i-1]. If there is no such element, it
returns -1. Let the returned value be j. If j is -1, then we don’t need to do anything as arr[i]
is already the greatest element among arr[0..i]. Otherwise we need to put arr[i] just before
arr[j].
So how to apply flip operations to put arr[i] just before arr[j] using values of i and j. Let us
take an example to understand this. Let i be 6 and current array be {12, 15, 18, 30, 35, 40,
20, 6, 90, 80}. To put 20 at its new place, the array should be changed to {12, 15, 18, 20,
30, 35, 40, 6, 90, 80}. We apply following steps to put 20 at its new place.
1) Find j using ceilSearch (In the above example j is 3).
2) flip(arr, j-1) (array becomes {18, 15, 12, 30, 35, 40, 20, 6, 90, 80})
3) flip(arr, i-1); (array becomes {40, 35, 30, 12, 15, 18, 20, 6, 90, 80})
4) flip(arr, i); (array becomes {20, 18, 15, 12, 30, 35, 40, 6, 90, 80})
5) flip(arr, j); (array becomes {12, 15, 18, 20, 30, 35, 40, 6, 90, 80})
Following is C implementation of the above algorithm.
C
#include <stdlib.h>
#include <stdio.h>
/* A Binary Search based function to get index of ceiling of x in
arr[low..high] */
int ceilSearch(int arr[], int low, int high, int x)
{
int mid;
/* If x is smaller than or equal to the first element,
then return the first element */
if(x <= arr[low])
return low;
/* If x is greater than the last element, then return -1 */
if(x > arr[high])
return -1;
/* get the index of middle element of arr[low..high]*/
mid = (low + high)/2; /* low + (high – low)/2 */
/* If x is same as middle element, then return mid */
if(arr[mid] == x)
return mid;
/* If x is greater than arr[mid], then either arr[mid + 1]
is ceiling of x, or ceiling lies in arr[mid+1...high] */
41
Chapter 4. A Pancake Sorting Problem
if(arr[mid] < x)
{
if(mid + 1 <= high && x <= arr[mid+1])
return mid + 1;
else
return ceilSearch(arr, mid+1, high, x);
}
/* If x is smaller than arr[mid], then either arr[mid]
is ceiling of x or ceiling lies in arr[mid-1...high] */
if (mid - 1 >= low && x > arr[mid-1])
return mid;
else
return ceilSearch(arr, low, mid - 1, x);
}
/* Reverses arr[0..i] */
void flip(int arr[], int i)
{
int temp, start = 0;
while (start < i)
{
temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
start++;
i--;
}
}
/* Function to sort an array using insertion sort, binary search and flip */
void insertionSort(int arr[], int size)
{
int i, j;
// Start from the second element and one by one insert arr[i]
// in already sorted arr[0..i-1]
for(i = 1; i < size; i++)
{
// Find the smallest element in arr[0..i-1] which is also greater than
// or equal to arr[i]
int j = ceilSearch(arr, 0, i-1, arr[i]);
// Check if there was no element greater than arr[i]
if (j != -1)
{
// Put arr[i] before arr[j] using following four flip operations
flip(arr, j-1);
42
Chapter 4. A Pancake Sorting Problem
flip(arr, i-1);
flip(arr, i);
flip(arr, j);
}
}
}
/* A utility function to print an array of size n */
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; ++i)
printf("%d ", arr[i]);
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = {18, 40, 35, 12, 30, 35, 20, 6, 90, 80};
int n = sizeof(arr)/sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
Python
43
Chapter 4. A Pancake Sorting Problem
44
Chapter 4. A Pancake Sorting Problem
Output:
6 12 18 20 30 35 35 40 80 90
Source
https://www.geeksforgeeks.org/a-pancake-sorting-question/
45
Chapter 5
First example: 7 8 5 4 9 2
Input :pass 1:|7 8 5 4 9 2|
pass 2: 2|8 5 4 7|9
pass 3: 2 4|5 7|8 9
Output :A sorted array: 2 4 5 7 8 9
second example: 23 78 45 8 32 56 1
Input :pass 1:|23 78 45 8 32 56 1|
pass 2: 1|23 45 8 32 56 |78
pass 3: 1 8|45 23 32|56 78
pass 4: 1 8 23 |32|45 56 78
in a case of odd elements, so one element
left for sorting, so sorting stops and the
array is sorted.
Output : A sorted array: 1 8 23 32 45 56 78
46
Chapter 5. A sorting algorithm that slightly improves on selection sort
Output:
Sorted array: 1 8 23 32 45 56 78
47
Chapter 5. A sorting algorithm that slightly improves on selection sort
Source
https://www.geeksforgeeks.org/sorting-algorithm-slightly-improves-selection-sort/
48
Chapter 6
Input: [0, 0, 0]
Output: 1
The solution should do only one scan of the input array and should not use any extra space.
i.e. expected time complexity is O(n) and auxiliary space is O(1).
One simple solution is to use set. For each element of the input array, we insert its absolute
value in the set. As set doesn’t support duplicate elements, the element’s absolute value
will be inserted only once. Therefore, the required count is size of the set.
Below is the implementation of the idea.
C++
49
Chapter 6. Absolute distinct count in a sorted array
Java
50
Chapter 6. Absolute distinct count in a sorted array
Output :
The above implementation takes O(n) extra space, how to do in O(1) extra
space?
The idea is to take advantage of the fact that the array is already Sorted. We initialize
the count of distinct elements to number of elements in the array. We start with two index
variables from two corners of the array and check for pair in the input array with sum as
0. If pair with 0 sum is found or duplicates are encountered, we decrement the count of
distinct elements.Finally we return the updated count.
Below is C++ implementation of the idea.
51
Chapter 6. Absolute distinct count in a sorted array
52
Chapter 6. Absolute distinct count in a sorted array
int main()
{
int arr[] = {-2, -1, 0, 1, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Count of absolute distinct values : "
<< distinctCount(arr, n);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/absolute-distinct-count-array-sorted-absolute-values/
53
Chapter 7
Input : bAwutndekWEdkd
Output :AbEdWddekkntuw
Explanation:
Here we can see that letter ‘A’, ’E’, ’W’ are sorted
as well as letters “b, d, d, d, e, k, k, n, t, u, w” are sorted
but both appears alternately in the string as far as possible.
Input :abbfDDhGFBvdFDGBNDasZVDFjkb
Output :BaBaDbDbDbDdDfFhFjFkGsGvNVZ
54
Chapter 7. Alternate Lower Upper String Sort
{
int n = s.length();
// Count occurrences of individual lower case and
// upper case characters
int lCount[MAX] = { 0 }, uCount[MAX] = { 0 };
for (int i = 0; i < n; i++) {
if (isupper(s[i]))
uCount[s[i] - 'A']++;
else
lCount[s[i] - 'a']++;
}
// Traverse through count arrays and one by one
// pick characters. Below loop takes O(n) time
// considering the MAX is constant.
int i = 0, j = 0, k = 0;
while (k < n) {
while (i < MAX && uCount[i] == 0)
i++;
if (i < MAX) {
s[k++] = 'A' + i;
uCount[i]--;
}
while (j < MAX && lCount[j] == 0)
j++;
if (j < MAX) {
s[k++] = 'a' + j;
lCount[j]--;
}
}
}
// Driver code
int main()
{
string str = "bAwutndekWEdkd";
alternateSort(str);
cout << str << "\n";
}
Java
55
Chapter 7. Alternate Lower Upper String Sort
public class GfG{
private final static int MAX = 100;
// Function for alternate
// sorting of string
public static String alternateSort(String s1)
{
int n = s1.length();
char[] s = s1.toCharArray();
// Count occurrences of
// individual lower case and
// upper case characters
int[] lCount = new int[MAX];
int[] uCount = new int[MAX];
for (int i = 0; i < n; i++) {
if (Character.isUpperCase(s[i]))
uCount[s[i] - 'A']++;
else
lCount[s[i] - 'a']++;
}
// Traverse through count
// arrays and one by one
// pick characters.
// Below loop takes O(n) time
// considering the MAX is constant.
int i = 0, j = 0, k = 0;
while (k < n)
{
while (i < MAX && uCount[i] == 0)
i++;
if (i < MAX) {
s[k++] = (char)('A' + i);
uCount[i]--;
}
while (j < MAX && lCount[j] == 0)
j++;
if (j < MAX) {
56
Chapter 7. Alternate Lower Upper String Sort
C#
57
Chapter 7. Alternate Lower Upper String Sort
else
lCount[s[i] - 'a']++;
}
// Traverse through count
// arrays and one by one
// pick characters.
// Below loop takes O(n) time
// considering the MAX is constant.
while (k < n)
{
while (l < MAX && uCount[l] == 0)
l++;
if (l < MAX) {
s[k++] = (char)('A' + l);
uCount[l]--;
}
while (j < MAX && lCount[j] == 0)
j++;
if (j < MAX) {
s[k++] = (char)('a' + j);
lCount[j]--;
}
}
return (new String(s));
}
// Driver function
public static void Main()
{
String str = "bAwutndekWEdkd";
Console.Write(alternateSort(str));
}
}
// This code is contributed by parashar.
Output:
AbEdWddekkntuw
58
Chapter 7. Alternate Lower Upper String Sort
Source
https://www.geeksforgeeks.org/alternate-lower-upper-string-sort/
59
Chapter 8
60
Chapter 8. Alternate sorting of Linked list
int data;
struct Node* next;
};
// function to get a new node
Node* getNode(int data)
{
// allocate space for node
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Split the nodes of the given list into front and
// back halves, and return the two lists using the
// reference parameters. If the length is odd, the
// extra node should go in the front list. Uses the
// fast/slow pointer strategy.
void FrontBackSplit(Node* source,
Node** frontRef, Node** backRef)
{
Node* fast;
Node* slow;
if (source == NULL || source->next == NULL) {
// length < 2 cases
*frontRef = source;
*backRef = NULL;
}
else {
slow = source;
fast = source->next;
// Advance 'fast' two nodes, and
// advance 'slow' one node
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
// 'slow' is before the midpoint in the list,
// so split it in two at that point.
61
Chapter 8. Alternate sorting of Linked list
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
}
// function to merge two sorted lists in
// sorted order
Node* SortedMerge(Node* a, Node* b)
{
Node* result = NULL;
// Base cases
if (a == NULL)
return b;
else if (b == NULL)
return a;
// Pick either a or b, and recur
if (a->data <= b->data) {
result = a;
result->next = SortedMerge(a->next, b);
}
else {
result = b;
result->next = SortedMerge(a, b->next);
}
return result;
}
// sorts the linked list by changing
// next pointers (not data)
void MergeSort(Node** headRef)
{
Node* head = *headRef;
Node *a, *b;
// Base case -- length 0 or 1
if ((head == NULL) || (head->next == NULL))
return;
// Split head into 'a' and 'b' sublists
FrontBackSplit(head, &a, &b);
// Recursively sort the sublists
MergeSort(&a);
MergeSort(&b);
62
Chapter 8. Alternate sorting of Linked list
// merge the two sorted lists together
*headRef = SortedMerge(a, b);
}
// function to reverse the linked list
static void reverse(Node** head_ref)
{
Node* prev = NULL;
Node* current = *head_ref;
Node* next;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
// function to alternately merge two lists
void alternateMerge(Node* head1, Node* head2)
{
Node *p, *q;
while (head1 != NULL && head2 != NULL) {
// merging nodes alternately by
// making the desired links
p = head1->next;
head1->next = head2;
head1 = p;
q = head2->next;
head2->next = head1;
head2 = q;
}
}
// function for alternative sort of the
// linked list
Node* altSortForLinkedList(Node* head)
{
// sort the linked list
MergeSort(&head);
Node *front, *back;
63
Chapter 8. Alternate sorting of Linked list
Output:
64
Chapter 8. Alternate sorting of Linked list
Original list: 10 9 8 7 6 5
Modified list: 5 10 6 9 7 8
Source
https://www.geeksforgeeks.org/alternate-sorting-linked-list/
65
Chapter 9
Alternative Sorting
A simple solution is to first print maximum element, then minimum, then second maxi-
mum, and so on. Time complexity of this approach is O(n2 ).
An efficient solution involves following steps.
1) Sort input array using a O(n Log n) algorithm.
2) We maintain two pointers, one from beginning and one from end in sorted array. We
alternatively print elements pointed by two pointers and move them toward each other.
C++
66
Chapter 9. Alternative Sorting
sort(arr, arr+n);
// Printing the last element of array
// first and then first element and then
// second last element and then second
// element and so on.
int i = 0, j = n-1;
while (i < j) {
cout << arr[j--] << " ";
cout << arr[i++] << " ";
}
// If the total element in array is odd
// then print the last middle element.
if (n % 2 != 0)
cout << arr[i];
}
// Driver code
int main()
{
int arr[] = {1, 12, 4, 6, 7, 10};
int n = sizeof(arr)/sizeof(arr[0]);
alternateSort(arr, n);
return 0;
}
Java
67
Chapter 9. Alternative Sorting
Python3
68
Chapter 9. Alternative Sorting
print(arr[i])
# Driver code
arr = [1, 12, 4, 6, 7, 10]
n = len(arr)
alternateSort(arr, n)
# This code is contributed by
# Smitha Dinesh Semwal
C#
69
Chapter 9. Alternative Sorting
}
// This article is contributed by vt_m.
PHP
<?php
// PHP program to print an array in
// alternate sorted manner.
// Function to print alternate
// sorted values
function alternateSort($arr, $n)
{
// Sorting the array
sort($arr);
// Printing the last element
// of array first and then
// first element and then second
// last element and then second
// element and so on.
$i = 0;
$j = $n - 1;
while ($i < $j)
{
echo $arr[$j--]." ";
echo $arr[$i++]." ";
}
// If the total element in array
// is odd then print the last
// middle element.
if ($n % 2 != 0)
echo $arr[$i];
}
// Driver code
$arr= array(1, 12, 4, 6, 7, 10);
$n = sizeof($arr) / sizeof($arr[0]);
alternateSort($arr, $n);
// This code is contributed by Mithun Kumar
?>
Output :
70
Chapter 9. Alternative Sorting
12 1 10 4 7 6
Source
https://www.geeksforgeeks.org/alternative-sorting/
71
Chapter 10
72
Chapter 10. An Insertion Sort time complexity question
If we analyze the input carefully we see that every element is only one position away from
its position in sorted array. The outer for loop will run till ‘n’ and the inner while loop
would take “constant” steps of 1 swap and 2 comparisons. Since, while loop takes constant
time and for loop runs for ‘n’ element, so overall complexity is O(n)
Alternate Answer : Another way to look at this is, time taken by Insertion Sort is pro-
portional to number of inversions in an array. In above example type, number of inversions
is n/2, so overall time complexity is O(n)
Source
https://www.geeksforgeeks.org/insertion-sort-time-complexity-question/
73
Chapter 11
Implementation:
74
Chapter 11. Asymptotic Analysis and comparison of sorting algorithms
75
Chapter 11. Asymptotic Analysis and comparison of sorting algorithms
76
Chapter 11. Asymptotic Analysis and comparison of sorting algorithms
}
}
void test_sorting_runtimes(int size,int num_of_times)
{
// Measuring the runtime of the sorting algorithms
int number_of_times = num_of_times;
int t = number_of_times;
int n = size;
double insertion_sort_time = 0, merge_sort_time = 0;
double merge_sort_and_insertion_sort_mix_time = 0, qsort_time = 0;
while(t--)
{
clock_t start, end;
int *a = generate_random_array(n);
int *b = copy_array(a,n);
start = clock();
insertion_sort_asc(b,0,n-1);
end = clock();
insertion_sort_time += ((double) (end - start)) / CLOCKS_PER_SEC;
free(b);
int *c = copy_array(a,n);
start = clock();
merge_sort(c,n);
end = clock();
merge_sort_time += ((double) (end - start)) / CLOCKS_PER_SEC;
free(c);
int *d = copy_array(a,n);
start = clock();
insertion_and_merge_sort_combine(d,0,n-1,40);
end = clock();
merge_sort_and_insertion_sort_mix_time+=((double) (end - start))/CLOCKS_PER_SEC;
free(d);
start = clock();
qsort(a,n,sizeof(int),cmpfunc);
end = clock();
qsort_time += ((double) (end - start)) / CLOCKS_PER_SEC;
free(a);
}
insertion_sort_time /= number_of_times;
merge_sort_time /= number_of_times;
merge_sort_and_insertion_sort_mix_time /= number_of_times;
qsort_time /= number_of_times;
printf("\nTime taken to sort:\n"
"%-35s %f\n"
"%-35s %f\n"
77
Chapter 11. Asymptotic Analysis and comparison of sorting algorithms
"%-35s %f\n"
"%-35s %f\n\n",
"(i)Insertion sort: ",
insertion_sort_time,
"(ii)Merge sort: ",
merge_sort_time,
"(iii)Insertion-mergesort-hybrid: ",
merge_sort_and_insertion_sort_mix_time,
"(iv)Qsort library function: ",
qsort_time);
}
int main(int argc, char const *argv[])
{
int t;
scanf("%d", &t);
while(t--)
{
int size, num_of_times;
scanf("%d %d", &size, &num_of_times);
test_sorting_runtimes(size,num_of_times);
}
return 0;
}
• Merge sort: Follows the divide-and-conquer approach. For input sizes of the order
10^5 this algorithm is of the right choice. It renders insertion sort impractical for such
large input sizes.
• Combined version of insertion sort and merge sort: I have tweaked the logic of
merge sort a little bit to achieve a considerably better running time for smaller input
sizes. As we know, merge sort splits its input into two halves until it is trivial enough
to sort the elements. But here, when the input size falls below a threshold such as ’n’
< 40 then this hybrid algorithm makes a call to traditional insertion sort procedure.
From the fact that insertion sort runs faster on smaller inputs and merge sort runs
faster on larger inputs, this algorithm makes best use both the worlds.
• Quick sort: I have not implemented this procedure. This is the library function
qsort() which is available in . I have considered this algorithm in order to know the
significance of implementation. It requires a great deal of programming expertise
to minimize the number of steps and make at most use of the underlying language
primitives to implement an algorithm in the best way possible. This is the main reason
why it is recommended to use library functions. They are written to handle anything
78
Chapter 11. Asymptotic Analysis and comparison of sorting algorithms
and everything. They optimize to the maximum extent possible. And before I forget,
from my analysis qsort() runs blazingly fast on virtually any input size!
The Analysis:
• Input: The user has to supply the number of times he/she wants to test the algorithm
corresponding to number of test cases. For each test case the user must enter two space
separated integers denoting the input size ’n’ and the ‘num_of_times’ denoting the
number of times he/she wants to run the analysis and take average. (Clarification: If
‘num_of_times’ is 10 then each of the algorithm specified above runs 10 times and
the average is taken. This is done because the input array is generated randomly
corresponding to the input size which you specify. The input array could be all sorted.
Our it could correspond to the worst case .i.e. descending order. In order to avoid
running times of such input arrays. The algorithm is run ‘num_of_times‘ and the
average is taken.)
clock() routine and CLOCKS_PER_SEC macro from is used to measure the time
taken.
Compilation: I have written the above code in Linux environment (Ubuntu 16.04 LTS).
Copy the code snippet above. Compile it using gcc, key in the inputs as specified and
admire the power of sorting algorithms!
• Results: As you can see for small input sizes, insertion sort beats merge sort by 2
* 10^-6 sec. But this difference in time is not so significant. On the other hand, the
hybrid algorithm and qsort() library function, both perform as good as insertion sort.
The input size is now increased by approximately 100 times to n = 1000 from n = 30.
The difference is now tangible. Merge sort runs 10 times faster than insertion sort.
There is again a tie between the performance of the hybrid algorithm and the qsort()
routine. This suggests that the qsort() is implemented in a way which is more or less
similar to our hybrid algorithm i.e., switching between different algorithms to make
the best out of them.
79
Chapter 11. Asymptotic Analysis and comparison of sorting algorithms
Finally, the input size is increased to 10^5 (1 Lakh!) which is most probably the ideal
size used in practical scenario’s. Compared to the previous input n = 1000 where
merge sort beat insertion sort by running 10 times faster, here the difference is even
more significant. Merge sort beats insertion sort by 100 times!
The hybrid algorithm which we have written in fact does out perform the traditional
merge sort by running 0.01 sec faster. And lastly, qsort() the library function, finally
proves us that implementation also plays a crucial role while measuring the running
times meticulously by running 3 milliseconds faster! �
Note: Do not run the above program with n >= 10^6 since it will take a lot of computing
power. Thank you and Happy coding! �
Source
https://www.geeksforgeeks.org/asymptotic-analysis-comparison-sorting-algorithms/
80
Chapter 12
Sorting of {7, 2, 1, 4, 2} using Bead Sort. Beads fall down one by one if there is space
below.
1. Like in the image above the beads represent the following numbers from top to bottom
: 7, 2, 1, 4, 2. Now, imagine that this is the position of the beads at time t = 0 and
with every passing second the beads will fall down by one level provided there is no
bead already present below them. In such a case, they just rest upon the bead below
them.(Rods are numbered from left to right and levels are numbered from the bottom
as 1, 2, ………. n.)
2. Now, at time t = 1 the bottom 2 beads in the first two rods from the left stay at
their positions while the second bead from the top from the second rod comes down
by one level to rest upon the bead below it. The beads in the 3rd and 4th rod at level
2 come down to level 1. Simultaneously, the beads in the rods 3 to 7 come down by
one level. Now, the numbers from top to bottom become: 2, 6, 2, 2, 4.
3. This goes on till time t = 4 where we get the sorted sequence of numbers from top
to bottom which is: 1, 2, 2, 4, 7.
81
Chapter 12. Bead Sort A Natural Sorting Algorithm
82
Chapter 12. Bead Sort A Natural Sorting Algorithm
Output:
1 1 1 3 4 5 7 20
83
Chapter 12. Bead Sort A Natural Sorting Algorithm
Time Complexity:
The algorithm’s run–time complexity ranges from O(1) to O(S) (S is the sum of the input
integers) depending on the user’s perspective. Finally, three possible implementations are
suggested.
1. O(1) : Dropping all beads together as a single (simultaneous) operation. This com-
plexity cannot be implemented in practice.
2. O( ): In a realistic physical model that uses gravity, the time it takes to let
the beads fall is proportional to the square root of the maximum height, which is
proportional to n.
3. O(n) : Dropping the row of beads in the frame (representing a number) as a distinct
operation since the number of rows is equal to n.
4. O(S) : Dropping each and every bead’ as a separate operation since S is the sum of
all the beads.
Like the Pigeonhole sort, bead sort is unusual in that in worst case it can perform faster
than O( ), the fastest performance possible for a comparison sort in worst case.
This is possible because the key for a bead sort is always a positive integer and bead sort
exploits its structure.
Space Complexity: Bead sort is the record-holder as for waste. The costs for the extra
memory exceed the costs for storing the array itself. Its memory complexity is O( )
References:
• https://www.wikiwand.com/en/Bead_sort
• https://kukuruku.co/post/bead-sort/
• https://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
• https://www.cs.auckland.ac.nz/~mjd/misc/BeadSort5.pdf
Source
https://www.geeksforgeeks.org/bead-sort-natural-sorting-algorithm/
84
Chapter 13
85
Chapter 13. Binary Insertion Sort
Java
86
Chapter 13. Binary Insertion Sort
new GFG().sort(arr);
for(int i=0; i<arr.length; i++)
System.out.print(arr[i]+" ");
}
public void sort(int array[])
{
for (int i = 1; i < array.length; i++)
{
int x = array[i];
// Find location to insert using binary search
int j = Math.abs(Arrays.binarySearch(array, 0, i, x) + 1);
//Shifting array to one location right
System.arraycopy(array, j, array, j+1, i-j);
//Placing element at its correct location
array[j] = x;
}
}
}
// Code contributed by Mohit Gupta_OMG
Python
87
Chapter 13. Binary Insertion Sort
mid = (start+end)/2
if arr[mid] < val:
return binary_search(arr, val, mid+1, end)
elif arr[mid] > val:
return binary_search(arr, val, start, mid-1)
else:
return mid
def insertion_sort(arr):
for i in xrange(1, len(arr)):
val = arr[i]
j = binary_search(arr, val, 0, i-1)
arr = arr[:j] + [val] + arr[j:i] + arr[i+1:]
return arr
print("Sorted array:")
print insertion_sort([37, 23, 0, 17, 12, 72, 31,
46, 100, 88, 54])
# Code contributed by Mohit Gupta_OMG
C#
// C# Program implementing
// binary insertion sort
using System;
class GFG {
public static void Main()
{
int []arr = {37, 23, 0, 17, 12, 72, 31,
46, 100, 88, 54 };
sort(arr);
for(int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
public static void sort(int []array)
{
for (int i = 1; i < array.Length; i++)
{
int x = array[i];
// Find location to insert using
88
Chapter 13. Binary Insertion Sort
Output:
Sorted array:
0 12 17 23 31 37 46 54 72 88 100
Time Complexity: The algorithm as a whole still has a running worst case running time
of O(n2 ) because of the series of swaps required for each insertion.
This article is contributed by Amit Auddy. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal, SayanMaiti, Shubhaw Kumar
Source
https://www.geeksforgeeks.org/binary-insertion-sort/
89
Chapter 14
Bitonic Sort
To understand Bitonic Sort, we must first understand what is Bitonic Sequence and how to
make a given sequence Bitonic.
Bitonic Sequence
A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array
arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that
1. A sequence, sorted in increasing order is considered Bitonic with the decreasing part as
empty. Similarly, decreasing order sequence is considered Bitonic with the increasing
part as empty.
90
Chapter 14. Bitonic Sort
and x3 in descending order. We then concatenate the two pairs to form a 4 element bitonic
sequence.
Next, we take two 4 element bitonic sequences, sorting one in ascending order, the other in
descending order (using the Bitonic Sort which we will discuss below), and so on, until we
obtain the bitonic sequence.
Example:
Convert the following sequence to bitonic sequence: 3, 7, 4, 8, 6, 2, 1, 5
Step 1: Consider each 2-consecutive elements as bitonic sequence and apply bitonic sort
on each 2- pair elements. In next step, take two 4 element bitonic sequences and so on.
Note: x0 and x1 are sorted in ascending order and x2 and x3 in descending order and so
on
Step 2: Two 4 element bitonic sequences : A(3,7,8,4) and B(2,6,5,1) with comparator
length as 2
91
Chapter 14. Bitonic Sort
3, 4, 7, 8, 6, 5, 2, 1
Bitonic Sorting
It mainly involves two steps.
1. Forming a bitonic sequence (discussed above in detail). After this step we reach the
fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}
2. Creating one sorted sequence from bitonic sequence : After first step, first half is
sorted in increasing order and second half in decreasing order.
We compare first element of first half with first element of second half, then second
element of first half with second element of second and so on. We exchange elements
if an element of first half is smaller.
After above compare and exchange steps, we get two bitonic sequences in array. See
fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we
take a closer look at the elements, we can notice that there are two bitonic sequences
of length n/2 such that all elements in first bitnic sequence {3, 4, 2, 1} are smaller
than all elements of second bitonic sequence {6, 5, 7, 8}.
We repeat the same process within two bitonic sequences and we get four bitonic
sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller
and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4,
6, 5, 7, 8}.
If we repeat this process one more time we get 8 bitonic sequences of size n/8 which
is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one
element, we get the sorted array.
92
Chapter 14. Bitonic Sort
93
Chapter 14. Bitonic Sort
}
}
/* This function first produces a bitonic sequence by recursively
sorting its two halves in opposite sorting orders, and then
calls bitonicMerge to make them in the same order */
void bitonicSort(int a[],int low, int cnt, int dir)
{
if (cnt>1)
{
int k = cnt/2;
// sort in ascending order since dir here is 1
bitonicSort(a, low, k, 1);
// sort in descending order since dir here is 0
bitonicSort(a, low+k, k, 0);
// Will merge wole sequence in ascending order
// since dir=1.
bitonicMerge(a,low, cnt, dir);
}
}
/* Caller of bitonicSort for sorting the entire array of
length N in ASCENDING order */
void sort(int a[], int N, int up)
{
bitonicSort(a,0, N, up);
}
// Driver code
int main()
{
int a[]= {3, 7, 4, 8, 6, 2, 1, 5};
int N = sizeof(a)/sizeof(a[0]);
int up = 1; // means sort in ascending order
sort(a, N, up);
printf("Sorted array: \n");
for (int i=0; i<N; i++)
printf("%d ", a[i]);
return 0;
}
Java
94
Chapter 14. Bitonic Sort
95
Chapter 14. Bitonic Sort
Python
96
Chapter 14. Bitonic Sort
if (dire==1 and a[i] > a[j]) or (dire==0 and a[i] < a[j]):
a[i],a[j] = a[j],a[i]
# It recursively sorts a bitonic sequence in ascending order,
# if dir = 1, and in descending order otherwise (means dir=0).
# The sequence to be sorted starts at index position low,
# the parameter cnt is the number of elements to be sorted.
def bitonicMerge(a, low, cnt, dire):
if cnt > 1:
k = cnt/2
for i in range(low , low+k):
compAndSwap(a, i, i+k, dire)
bitonicMerge(a, low, k, dire)
bitonicMerge(a, low+k, k, dire)
# This funcion first produces a bitonic sequence by recursively
# sorting its two halves in opposite sorting orders, and then
# calls bitonicMerge to make them in the same order
def bitonicSort(a, low, cnt,dire):
if cnt > 1:
k = cnt/2
bitonicSort(a, low, k, 1)
bitonicSort(a, low+k, k, 0)
bitonicMerge(a, low, cnt, dire)
# Caller of bitonicSort for sorting the entire array of length N
# in ASCENDING order
def sort(a,N, up):
bitonicSort(a,0, N, up)
# Driver code to test above
a = [3, 7, 4, 8, 6, 2, 1, 5]
n = len(a)
up = 1
sort(a, n, up)
print ("\n\nSorted array is")
for i in range(n):
print("%d" %a[i]),
Output:
Sorted array:
1 2 3 4 5 6 7 8
97
Chapter 14. Bitonic Sort
To form a sorted sequence of length n from two sorted sequences of length n/2, log(n)
comparisons are required (for example: log(8) = 3 when sequence size. Therefore, The
number of comparisons T(n) of the entire sorting is given by:
T(n) = log(n) + T(n/2)
The solution of this recurrence equation is
T(n) = log(n) + log(n)-1 + log(n)-2 + … + 1 = log(n) · (log(n)+1) / 2
As, each stage of the sorting network consists of n/2 comparators. Therefore total Θ(n
log2 n) comparators.
References:
1. https://www.youtube.com/watch?v=GEQ8y26blEY
2. http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm
3. https://en.wikipedia.org/wiki/Bitonic_sorter
Source
https://www.geeksforgeeks.org/bitonic-sort/
98
Chapter 15
PseudoCode:
Example:
Let us consider an example array ( 3 2 5 1 0 4 )
4 5 0 3 2 1 (1st shuffling)
4 1 3 2 5 0 (2ndshuffling)
1 0 3 2 5 4 (3rd shuffling)
3 1 0 2 4 5 (4th shuffling)
1 4 5 0 3 2 (5th shuffling)
.
.
.
0 1 2 3 4 5 (nth shuffling)—— Sorted Array
Here, n is unknown because algorithm doesn’t known in which step the resultant permuta-
tion will come out to be sorted.
C++
99
Chapter 15. BogoSort or Permutation Sort
100
Chapter 15. BogoSort or Permutation Sort
Java
101
Chapter 15. BogoSort or Permutation Sort
public static void main(String[] args)
{
//Enter array to be sorted here
int[] a = {3, 2, 5, 1, 0, 4};
BogoSort ob = new BogoSort();
ob.bogoSort(a);
System.out.print("Sorted array: ");
ob.printArray(a);
}
}
Python
Output:
102
Chapter 15. BogoSort or Permutation Sort
Sorted array :
0 1 2 3 4 5
Time Complexity:
Source
https://www.geeksforgeeks.org/bogosort-permutation-sort/
103
Chapter 16
Bubble Sort
104
Chapter 16. Bubble Sort
Java
105
Chapter 16. Bubble Sort
Python
106
Chapter 16. Bubble Sort
C#
107
Chapter 16. Bubble Sort
printArray(arr);
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program for implementation
// of Bubble Sort
function bubbleSort(&$arr)
{
$n = sizeof($arr);
// Traverse through all array elements
for($i = 0; $i < $n; $i++)
{
// Last i elements are already in place
for ($j = 0; $j < $n - $i - 1; $j++)
{
// traverse the array from 0 to n-i-1
// Swap if the element found is greater
// than the next element
if ($arr[$j] > $arr[$j+1])
{
$t = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $t;
}
}
}
}
// Driver code to test above
$arr = array(64, 34, 25, 12, 22, 11, 90);
$len = sizeof($arr);
bubbleSort($arr);
echo "Sorted array : \n";
for ($i = 0; $i < $len; $i++)
echo $arr[$i]." ";
// This code is contributed by ChitraNayal.
108
Chapter 16. Bubble Sort
?>
Output:
Sorted array:
11 12 22 25 34 64 90
<!—-Illustration :
—>
Optimized Implementation:
The above function always runs O(n^2) time even if the array is sorted. It can be optimized
by stopping the algorithm if inner loop didn’t cause any swap.
CPP
109
Chapter 16. Bubble Sort
110
Chapter 16. Bubble Sort
Java
111
Chapter 16. Bubble Sort
int n = arr.length;
bubbleSort(arr, n);
System.out.println("Sorted array: ");
printArray(arr, n);
}
}
// This code is contributed
// by Nikita Tiwari.
Python3
112
Chapter 16. Bubble Sort
C#
// Optimized C# implementation
// of Bubble sort
using System;
class GFG
{
// An optimized version of Bubble Sort
static void bubbleSort(int []arr, int n)
{
int i, j, temp;
bool swapped;
for (i = 0; i < n - 1; i++)
{
swapped = false;
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// IF no two elements were
// swapped by inner loop, then break
if (swapped == false)
break;
}
}
// Function to print an array
static void printArray(int []arr, int size)
{
int i;
for (i = 0; i < size; i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
113
Chapter 16. Bubble Sort
PHP
<?php
// PHP Optimized implementation
// of Bubble sort
// An optimized version of Bubble Sort
function bubbleSort(&$arr)
{
$n = sizeof($arr);
// Traverse through all array elements
for($i = 0; $i < $n; $i++)
{
$swapped = False;
// Last i elements are already
// in place
for ($j = 0; $j < $n - $i - 1; $j++)
{
// traverse the array from 0 to
// n-i-1. Swap if the element
// found is greater than the
// next element
if ($arr[$j] > $arr[$j+1])
{
$t = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $t;
$swapped = True;
}
}
// IF no two elements were swapped
114
Chapter 16. Bubble Sort
Output:
Sorted array:
11 12 22 25 34 64 90
Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array
is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already
sorted.
Sorting In Place: Yes
Stable: Yes
Due to its simplicity, bubble sort is often used to introduce the concept of a sorting algorithm.
In computer graphics it is popular for its capability to detect a very small error (like swap
of just two elements) in almost-sorted arrays and fix it with just linear complexity (2n).
For example, it is used in a polygon filling algorithm, where bounding lines are sorted by
their x coordinate at a specific scan line (a line parallel to x axis) and with incrementing y
their order changes (two elements are swapped) only at intersections of two lines (Source:
Wikipedia)
Snapshots:
115
Chapter 16. Bubble Sort
116
Chapter 16. Bubble Sort
• Selection Sort
• Insertion Sort
• Merge Sort
• Heap Sort
• QuickSort
• Radix Sort
• Counting Sort
• Bucket Sort
• ShellSort
117
Chapter 16. Bubble Sort
Source
https://www.geeksforgeeks.org/bubble-sort/
118
Chapter 17
Input : 5 4 3 2 1
Output : 1 2 3 4 5
Input : 2 1 3 5 4
Output :1 2 3 4 5
Explanation
As we do in the bubble sort, here also we check elements of two adjacent node whether
they are in ascending order or not, if not then we swap the element. We do this until every
element get its original position.
In 1st pass the largest element get its original position and in 2nd pass 2nd largest element
get its original position and in 3rd pass 3rd largest element get its original position and so
on.
And finally whole list get sorted.
Note: If the list is already sorted then it will do only one pass.
119
Chapter 17. Bubble Sort On Doubly Linked List
// structure of a node
struct Node {
int data;
Node* prev;
Node* next;
};
/* Function to insert a node at the beginning of a linked list */
void insertAtTheBegin(struct Node **start_ref, int data)
{
struct Node *ptr1 = new Node;
ptr1->data = data;
ptr1->next = *start_ref;
if (*start_ref != NULL)
(*start_ref)->prev = ptr1;
*start_ref = ptr1;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *start)
{
struct Node *temp = start;
cout << endl;
while (temp!=NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
/* Bubble sort the given linked list */
void bubbleSort(struct Node *start)
{
int swapped, i;
struct Node *ptr1;
struct Node *lptr = NULL;
/* Checking for empty list */
if (start == NULL)
return;
do
{
swapped = 0;
ptr1 = start;
while (ptr1->next != lptr)
{
120
Chapter 17. Bubble Sort On Doubly Linked List
Output:
121
Chapter 17. Bubble Sort On Doubly Linked List
Source
https://www.geeksforgeeks.org/bubble-sort-on-doubly-linked-list/
122
Chapter 18
123
Chapter 18. Bubble sort using two Stacks
import java.util.Stack;
public class Test
{
// Method for bubble sort using Stack
static void bubbleSortStack(int arr[], int n)
{
Stack<Integer> s1 = new Stack<>();
// Push all elements of array in 1st stack
for (int num : arr)
s1.push(num);
Stack<Integer> s2 = new Stack<>();
for (int i = 0; i < n; i++)
{
// alternatively
if (i % 2 == 0)
{
while (!s1.isEmpty())
{
int t = s1.pop();
if (s2.isEmpty())
s2.push(t);
else
{
if (s2.peek() > t)
{
// swapping
int temp = s2.pop();
s2.push(t);
s2.push(temp);
}
else
{
s2.push(t);
}
}
}
// tricky step
arr[n-1-i] = s2.pop();
}
else
{
while(!s2.isEmpty())
124
Chapter 18. Bubble sort using two Stacks
{
int t = s2.pop();
if (s1.isEmpty())
s1.push(t);
else
{
if (s1.peek() > t)
{
// swapping
int temp = s1.pop();
s1.push(t);
s1.push(temp);
}
else
s1.push(t);
}
}
// tricky step
arr[n-1-i] = s1.pop();
}
}
System.out.println(Arrays.toString(arr));
}
// Driver Method
public static void main(String[] args)
{
int arr[] = {15, 12, 44, 2, 5, 10};
bubbleSortStack(arr, arr.length);
}
}
Output:
Source
https://www.geeksforgeeks.org/bubble-sort-using-two-stacks/
125
Chapter 19
Bucket Sort
bucketSort(arr[], n)
1) Create n empty buckets (Or lists).
2) Do following for every array element arr[i].
.......a) Insert arr[i] into bucket[n*array[i]]
3) Sort individual buckets using insertion sort.
4) Concatenate all sorted buckets.
126
Chapter 19. Bucket Sort
Time Complexity: If we assume that insertion in a bucket takes O(1) time then steps 1
and 2 of the above algorithm clearly take O(n) time. The O(1) is easily possible if we use a
linked list to represent a bucket (In the following code, C++ vector is used for simplicity).
Step 4 also takes O(n) time as there will be n items in all buckets.
The main step to analyze is step 3. This step also takes O(n) time on average if all numbers
are uniformly distributed (please refer CLRS book for more details)
Following is C++ implementation of the above algorithm.
127
Chapter 19. Bucket Sort
}
// 3) Sort individual buckets
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());
// 4) Concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < b[i].size(); j++)
arr[index++] = b[i][j];
}
/* Driver program to test above funtion */
int main()
{
float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
int n = sizeof(arr)/sizeof(arr[0]);
bucketSort(arr, n);
cout << "Sorted array is \n";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
Sorted array is
0.1234 0.3434 0.565 0.656 0.665 0.897
Snapshots:
128
Chapter 19. Bucket Sort
129
Chapter 19. Bucket Sort
130
Chapter 19. Bucket Sort
131
Chapter 19. Bucket Sort
132
Chapter 19. Bucket Sort
133
Chapter 19. Bucket Sort
134
Chapter 19. Bucket Sort
135
Chapter 19. Bucket Sort
136
Chapter 19. Bucket Sort
• Selection Sort
• Bubble Sort
• Insertion Sort
• Merge Sort
• Heap Sort
• QuickSort
• Radix Sort
• Counting Sort
• ShellSort
Source
https://www.geeksforgeeks.org/bucket-sort-2/
137
Chapter 20
How to modify Bucket Sort to sort both positive and negative numbers?
Example:
sortMixed(arr[], n)
1) Split array into two parts
create two Empty vector Neg[], Pos[]
(for negative and positive element respectively)
Store all negative element in Neg[] by converting
into positive (Neg[i] = -1 * Arr[i] )
Store all +ve in pos[] (pos[i] = Arr[i])
2) Call function bucketSortPositive(Pos, pos.size())
Call function bucketSortPositive(Neg, Neg.size())
bucketSortPositive(arr[], n)
138
Chapter 20. Bucket Sort To Sort an Array with Negative Numbers
139
Chapter 20. Bucket Sort To Sort an Array with Negative Numbers
Output:
Sorted array is
-0.897 -0.1234 0 0.3434 0.565 0.656
Source
https://www.geeksforgeeks.org/bucket-sort-to-sort-an-array-with-negative-numbers/
140
Chapter 21
Source
https://www.geeksforgeeks.org/c-program-for-binary-insertion-sort/
C/C++
141
Chapter 21. C Program for Binary Insertion Sort
Please refer complete article on Binary Insertion Sort for more details!
142
Chapter 22
Source
https://www.geeksforgeeks.org/c-program-for-bubble-sort/
C/C++
143
Chapter 22. C Program for Bubble Sort
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
144
Chapter 23
Input : 10->30->20->5
Output : 5->10->20->30
Input : 20->4->3
Output : 3->4->20
145
Chapter 23. C Program for Bubble Sort on Linked List
146
Chapter 23. C Program for Bubble Sort on Linked List
while (temp!=NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
/* Bubble sort the given linked list */
void bubbleSort(struct Node *start)
{
int swapped, i;
struct Node *ptr1;
struct Node *lptr = NULL;
/* Checking for empty list */
if (start == NULL)
return;
do
{
swapped = 0;
ptr1 = start;
while (ptr1->next != lptr)
{
if (ptr1->data > ptr1->next->data)
{
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
while (swapped);
}
/* function to swap data of two nodes a and b*/
void swap(struct Node *a, struct Node *b)
{
int temp = a->data;
a->data = b->data;
b->data = temp;
}
Output:
147
Chapter 23. C Program for Bubble Sort on Linked List
Improved By : YugandharTripathi
Source
https://www.geeksforgeeks.org/c-program-bubble-sort-linked-list/
148
Chapter 24
Source
https://www.geeksforgeeks.org/c-program-for-recursive-insertion-sort/
C/C++
149
Chapter 24. C Program for Recursive Insertion Sort
if (n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive( arr, n-1 );
// Insert last element at its correct position
// in sorted array.
int last = arr[n-1];
int j = n-2;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > last)
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = last;
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
for (int i=0; i < n; i++)
cout << arr[i] <<" ";
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
insertionSortRecursive(arr, n);
printArray(arr, n);
return 0;
}
Please refer complete article on Recursive Insertion Sort for more details!
150
Chapter 25
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static int myCompare (const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char **) b);
}
void sort(const char *arr[], int n)
{
qsort (arr, n, sizeof (const char *), myCompare);
}
int main ()
{
const char *arr[] = {"GeeksforGeeks", "GeeksQuiz", "CLanguage"};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
printf("Given array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
151
Chapter 25. C Program to Sort an array of names or strings
sort(arr, n);
printf("\nSorted array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
return 0;
}
Output:
Given array is
0: GeeksforGeeks
1: GeeksQuiz
2: CLanguage
Sorted array is
0: CLanguage
1: GeeksQuiz
2: GeeksforGeekss
Source
https://www.geeksforgeeks.org/c-program-sort-array-names-strings/
152
Chapter 26
153
Chapter 26. C program to sort an array of strings using Selection Sort
int min_idx = i;
strcpy(minStr, arr[i]);
for (j = i+1; j < n; j++)
{
// If min is greater than arr[j]
if (strcmp(minStr, arr[j]) > 0)
{
// Make arr[j] as minStr and update min_idx
strcpy(minStr, arr[j]);
min_idx = j;
}
}
// Swap the found minimum element with the first element
if (min_idx != i)
{
char temp[MAX_LEN];
strcpy(temp, arr[i]); //swap item[pos] and item[i]
strcpy(arr[i], arr[min_idx]);
strcpy(arr[min_idx], temp);
}
}
}
// Driver code
int main()
{
char arr[][MAX_LEN] = {"GeeksforGeeks", "Practice.GeeksforGeeks",
"GeeksQuiz"};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
printf("Given array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
selectionSort(arr, n);
printf("\nSorted array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
return 0;
}
Output :
154
Chapter 26. C program to sort an array of strings using Selection Sort
Given array is
0: GeeksforGeeks
1: Practice.GeeksforGeeks
2: GeeksQuiz
Sorted array is
0: GeeksQuiz
1: GeeksforGeeks
2: Practice.GeeksforGeek
Source
https://www.geeksforgeeks.org/c-program-to-sort-an-array-of-strings-using-selection-sort-2/
155
Chapter 27
It requires a pointer to the array, the number of elements in the array, the size of each
element and a comparator function. We have discussed qsort comparator in detail here.
C++ Standard Library provides a similar function sort() that originated in the STL. We
have discussed C++ sort here. Following are prototypes of C++ sort() function.
156
Chapter 27. C qsort() vs C++ sort()
As the name suggests, qsort function uses QuickSort algorithm to sort the given array,
although the C standard does not require it to implement quicksort.
C++ sort function uses introsort which is a hybrid algorithm. Different implementations
use different algorithms. The GNU Standard C++ library, for example, uses a 3-part hybrid
sorting algorithm: introsort is performed first (introsort itself being a hybrid of quicksort
and heap sort) followed by an insertion sort on the result.
2. Complexity :
The C standard doesn’t talk about its complexity of qsort. The new C++11 standard
requires that the complexity of sort to be O(Nlog(N)) in the worst case. Previous versions of
C++ such as C++03 allow possible worst case scenario of O(N^2). Only average complexity
was required to be O(N log N).
3. Running time:
STL’s sort ran faster than C’s qsort, because C++’s templates generate optimized code for
a particular data type and a particular comparison function.
STL’s sort runs 20% to 50% faster than the hand-coded quicksort and 250% to 1000% faster
than the C qsort library function. C might be the fastest language but qsort is very slow.
When we tried to sort one million integers on C++14, Time taken by C qsort() was 0.247883
sec and time taken by C++ sort() was only 0.086125 sec
157
Chapter 27. C qsort() vs C++ sort()
Output :
C++ sort() is blazingly faster than qsort() on equivalent data due to inlining. sort() on a
container of integers will be compiled to use std::less::operator() by default, which will be
inlined and sort() will be comparing the integers directly. On the other hand, qsort() will
be making an indirect call through a function pointer for every comparison which compilers
fails to optimize.
4. Flexibility:
STL’s sort works for all data types and for different data containers like C arrays, C++
vectors, C++ deques, etc and other containers that can be written by the user. This kind
of flexibility is rather difficult to achieve in C.
5. Safety:
Compared to qsort, the templated sort is more type-safe since it does not require access to
data items through unsafe void pointers, as qsort does.
158
Chapter 27. C qsort() vs C++ sort()
References:
http://theory.stanford.edu/~amitp/rants/c++-vs-c
https://en.wikipedia.org/wiki/Sort_(C%2B%2B)
Source
https://www.geeksforgeeks.org/c-qsort-vs-c-sort/
159
Chapter 28
160
Chapter 28. C++ Program for Bubble Sort
Source
https://www.geeksforgeeks.org/cpp-program-for-bubble-sort/
161
Chapter 29
162
Chapter 29. C++ Program for Cycle Sort
We one by one consider all cycles. We first consider the cycle that includes first element.
We find correct position of first element, place it at its correct position, say j. We consider
old value of arr[j] and find its correct position, we keep doing this till all elements of
current cycle are placed at correct position, i.e., we don\’t come back to cycle starting point.
Source
https://www.geeksforgeeks.org/cpp-program-for-cycle-sort/
CPP
163
Chapter 29. C++ Program for Cycle Sort
164
Chapter 29. C++ Program for Cycle Sort
int main()
{
int arr[] = {1, 8, 3, 9, 10, 10, 2, 4 };
int n = sizeof(arr)/sizeof(arr[0]);
cycleSort(arr, n) ;
cout << "After sort : " <<endl;
for (int i =0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
After sort :
1 2 3 4 8 9 10 10
165
Chapter 30
The key process in quickSort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x.
All this should be done in linear time.
Pseudo Code for recursive QuickSort function :
166
Chapter 30. C++ Program for QuickSort
Source
https://www.geeksforgeeks.org/cpp-program-for-quicksort/
C/C++
/* C implementation QuickSort */
#include<stdio.h>
// A utility function to swap two elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
/* This function takes last element as pivot, places
the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot */
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
167
Chapter 30. C++ Program for QuickSort
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}
168
Chapter 31
Recursion Idea.
169
Chapter 31. C++ Program for Recursive Bubble Sort
Source
https://www.geeksforgeeks.org/cpp-program-for-recursive-bubble-sort/
C/C++
170
Chapter 31. C++ Program for Recursive Bubble Sort
Please refer complete article on Recursive Bubble Sort for more details!
171
Chapter 32
Source
https://www.geeksforgeeks.org/cpp-program-for-stooge-sort/
C++
172
Chapter 32. C++ Program for Stooge Sort
swap(arr[l], arr[h]);
// If there are more than 2 elements in
// the array
if(h-l+1>2)
{
int t = (h-l+1)/3;
// Recursively sort first 2/3 elements
stoogesort(arr, l, h-t);
// Recursively sort last 2/3 elements
stoogesort(arr, l+t, h);
// Recursively sort first 2/3 elements
// again to confirm
stoogesort(arr, l, h-t);
}
}
// Driver Code
int main()
{
int arr[] = {2, 4, 5, 3, 1};
int n = sizeof(arr)/sizeof(arr[0]);
// Calling Stooge Sort function to sort
// the array
stoogesort(arr, 0, n-1);
// Display the sorted array
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
1 2 3 4 5
173
Chapter 33
174
Chapter 33. C++ program for Sorting Dates using Selection Sort
input[i] = input[j];
input[j] = temp;
}
else if (input[i].year == input[j].year && input[i].month > input[j].month)
{
struct date temp = input[i];
input[i] = input[j];
input[j] = temp;
}
else if (input[i].year == input[j].year && input[i].month == input[j].month && input[
{
struct date temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}
}
for(int i=0; i<5; i++)
{
cout<<input[i].day<<" "<<input[i].month<<" "<<input[i].year;
cout<<endl;
}
}
This program is contributed by Dinesh T.P.D. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/c-program-for-sorting-dates-using-selection-sort/
175
Chapter 34
176
Chapter 34. Can QuickSort be implemented in O(nLogn) worst case time complexity?
/* A O(nLogn) time complexity function for sorting arr[l..h] */
void quickSort(int arr[], int l, int h)
{
if (l < h)
{
// Find size of current subarray
int n = h-l+1;
// Find median of arr[].
int med = kthSmallest(arr, l, h, n/2);
// Partition the array around median
int p = partition(arr, l, h, med);
// Recur for left and right of partition
quickSort(arr, l, p - 1);
quickSort(arr, p + 1, h);
}
}
// A simple function to find median of arr[]. This is called
// only for an array of size 5 in this program.
int findMedian(int arr[], int n)
{
sort(arr, arr+n); // Sort the array
return arr[n/2]; // Return middle element
}
// Returns k'th smallest element in arr[l..r] in worst case
// linear time. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT
int kthSmallest(int arr[], int l, int r, int k)
{
// If k is smaller than number of elements in array
if (k > 0 && k <= r - l + 1)
{
int n = r-l+1; // Number of elements in arr[l..r]
// Divide arr[] in groups of size 5, calculate median
// of every group and store it in median[] array.
int i, median[(n+4)/5]; // There will be floor((n+4)/5) groups;
for (i=0; i<n/5; i++)
median[i] = findMedian(arr+l+i*5, 5);
if (i*5 < n) //For last group with less than 5 elements
{
median[i] = findMedian(arr+l+i*5, n%5);
i++;
}
177
Chapter 34. Can QuickSort be implemented in O(nLogn) worst case time complexity?
// Find median of all medians using recursive call.
// If median[] has only one element, then no need
// of recursive call
int medOfMed = (i == 1)? median[i-1]:
kthSmallest(median, 0, i-1, i/2);
// Partition the array around a random element and
// get position of pivot element in sorted array
int pos = partition(arr, l, r, medOfMed);
// If position is same as k
if (pos-l == k-1)
return arr[pos];
if (pos-l > k-1) // If position is more, recur for left
return kthSmallest(arr, l, pos-1, k);
// Else recur for right subarray
return kthSmallest(arr, pos+1, r, k-pos+l-1);
}
// If k is more than number of elements in array
return INT_MAX;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// It searches for x in arr[l..r], and partitions the array
// around x.
int partition(int arr[], int l, int r, int x)
{
// Search for x in arr[l..r] and move it to end
int i;
for (i=l; i<r; i++)
if (arr[i] == x)
break;
swap(&arr[i], &arr[r]);
// Standard partition algorithm
i = l;
for (int j = l; j <= r - 1; j++)
{
if (arr[j] <= x)
178
Chapter 34. Can QuickSort be implemented in O(nLogn) worst case time complexity?
{
swap(&arr[i], &arr[j]);
i++;
}
}
swap(&arr[i], &arr[r]);
return i;
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver program to test above functions
int main()
{
int arr[] = {1000, 10, 7, 8, 9, 30, 900, 1, 5, 6, 20};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
cout << "Sorted array is\n";
printArray(arr, n);
return 0;
}
Output:
Sorted array is
1 5 6 7 8 9 10 20 30 900 1000
179
Chapter 34. Can QuickSort be implemented in O(nLogn) worst case time complexity?
Source
https://www.geeksforgeeks.org/can-quicksort-implemented-onlogn-worst-case-time-complexity/
180
Chapter 35
Step 2 : Starting from the root of the built Cartesian Tree, we push the nodes in a priority
queue.
181
Chapter 35. Cartesian Tree Sorting
Then we pop the node at the top of the priority queue and push the children of the popped
node in the priority queue in a pre-order manner.
1. Pop the node at the top of the priority queue and add it to a list.
2. Push left child of the popped node first (if present).
3. Push right child of the popped node next (if present).
182
Chapter 35. Cartesian Tree Sorting
max-heap Cartesian Tree) than the current one and then accordingly reconfigure links to
build the min-heap Cartesian tree.
Why not to use only priority queue?
One might wonder that using priority queue would anyway result in a sorted data if we
simply insert the numbers of the input array one by one in the priority queue (i.e- without
constructing the Cartesian tree).
But the time taken differs a lot.
Suppose we take the input array – {5, 10, 40, 30, 28}
If we simply insert the input array numbers one by one (without using a Cartesian tree),
then we may have to waste a lot of operations in adjusting the queue order everytime we
insert the numbers (just like a typical heap performs those operations when a new number
is inserted, as priority queue is nothing but a heap).
Whereas, here we can see that using a Cartesian tree took only 5 operations (see the above
two figures in which we are continuously pushing and popping the nodes of Cartesian tree),
which is linear as there are 5 numbers in the input array also. So we see that the best
case of Cartesian Tree sort is O(n), a thing where heap-sort will take much more number of
operations, because it doesn’t make advantage of the fact that the input data is partially
sorted.
Why pre-order traversal?
The answer to this is that since Cartesian Tree is basically a heap- data structure and hence
follows all the properties of a heap. Thus the root node is always smaller than both of its
children. Hence, we use a pre-order fashion popping-and-pushing as in this, the root node
is always pushed earlier than its children inside the priority queue and since the root node
is always less than both its child, so we don’t have to do extra operations inside the priority
queue.
Refer to the below figure for better understanding-
183
Chapter 35. Cartesian Tree Sorting
184
Chapter 35. Cartesian Tree Sorting
Node *buildCartesianTreeUtil(int root, int arr[],
int parent[], int leftchild[], int rightchild[])
{
if (root == -1)
return NULL;
Node *temp = new Node;
temp->data = arr[root];
temp->left = buildCartesianTreeUtil(leftchild[root],
arr, parent, leftchild, rightchild);
temp->right = buildCartesianTreeUtil(rightchild[root],
arr, parent, leftchild, rightchild);
return temp ;
}
// A function to create the Cartesian Tree in O(N) time
Node *buildCartesianTree(int arr[], int n)
{
// Arrays to hold the index of parent, left-child,
// right-child of each number in the input array
int parent[n],leftchild[n],rightchild[n];
// Initialize all array values as -1
memset(parent, -1, sizeof(parent));
memset(leftchild, -1, sizeof(leftchild));
memset(rightchild, -1, sizeof(rightchild));
// 'root' and 'last' stores the index of the root and the
// last processed of the Cartesian Tree.
// Initially we take root of the Cartesian Tree as the
// first element of the input array. This can change
// according to the algorithm
int root = 0, last;
// Starting from the second element of the input array
// to the last on scan across the elements, adding them
// one at a time.
for (int i=1; i<=n-1; i++)
{
last = i-1;
rightchild[i] = -1;
// Scan upward from the node's parent up to
// the root of the tree until a node is found
185
Chapter 35. Cartesian Tree Sorting
186
Chapter 35. Cartesian Tree Sorting
Output :
Time Complexity : O(n) best-case behaviour (when the input data is partially sorted),
O(n log n) worst-case behavior (when the input data is not partially sorted)
Auxiliary Space : We use a priority queue and a Cartesian tree data structure. Now, at
any moment of time the size of the priority queue doesn’t exceeds the size of the input array,
as we are constantly pushing and popping the nodes. Hence we are using O(n) auxiliary
space.
References :
https://en.wikipedia.org/wiki/Adaptive_sort
187
Chapter 35. Cartesian Tree Sorting
http://11011110.livejournal.com/283412.htmlhttp://gradbot.blogspot.in/2010/06/cartesian-tree-sort.
htmlhttp://www.keithschwarz.com/interesting/code/?dir=cartesian-tree-sorthttps:
//en.wikipedia.org/wiki/Cartesian_tree#Application_in_sorting
Source
https://www.geeksforgeeks.org/cartesian-tree-sorting/
188
Chapter 36
Check if a grid can become row-wise and column-wise sorted after adjacent swaps - Geeks-
forGeeks
Given a grid of size n x len filled with lowercase characters. We can swap two adjacent
characters in the same row and column. Now we have to check whether it is possible to
arrange in such a order that every row and every column in the grid is lexicographically
sorted.
Examples:
Input : abcde
fghij
olmkn
trpqs
xywuv
Output : Yes
Explanation :
The grid can be rearranged as
abcde
fghij
klmno
pqrst
uvwxy
The idea to do the above problem is really simple we can simply sort the characters in the
same row and then just
189
Chapter 36. Check if a grid can become row-wise and column-wise sorted after adjacent
swaps
check column vise if the new grid is sorted column vise or not. Please not that sorting is
possible with adjacent swaps (Bubble sort for example does only adjacent swaps)
The implementation of the above idea is given below.
C++
Python
190
Chapter 36. Check if a grid can become row-wise and column-wise sorted after adjacent
swaps
i = ''.join(sorted(i))
for i in range(l - 1):
for j in range(n):
if (v[i][j] > v[i + 1][j]):
return False
return True
# Driver code
v = [ "ebcda", "ihgfj", "klmno", "pqrst", "yvwxu" ]
l = 5 # Length of strings
if check(v, l):
print "Yes"
else:
print "No"
# This code is contributed by Sachin Bisht
Output:
Yes
Source
https://www.geeksforgeeks.org/check-grid-can-become-row-wise-column-wise-sorted-adjacent-swaps/
191
Chapter 37
Check if a queue can be sorted into another queue using a stack - GeeksforGeeks
Given a Queue consisting of first n natural numbers (in random order). The task is to check
whether the given Queue elements can be arranged in increasing order in another Queue
using a stack. The operation allowed are:
1. Push and pop elements from the stack
2. Pop (Or enqueue) from the given Queue.
3. Push (Or Dequeue) in the another Queue.
Examples :
Input : Queue[] = { 5, 1, 2, 3, 4 }
Output : Yes
Pop the first element of the given Queue i.e 5.
Push 5 into the stack.
Now, pop all the elements of the given Queue and push them to
second Queue.
Now, pop element 5 in the stack and push it to the second Queue.
Input : Queue[] = { 5, 1, 2, 6, 3, 4 }
Output : No
Push 5 to stack.
Pop 1, 2 from given Queue and push it to another Queue.
Pop 6 from given Queue and push to stack.
Pop 3, 4 from given Queue and push to second Queue.
Now, from using any of above operation, we cannot push 5
into the second Queue because it is below the 6 in the stack.
Observe, second Queue (which will contain the sorted element) takes inputs (or enqueue
elements) either from given Queue or Stack. So, next expected (which will initially be 1)
192
Chapter 37. Check if a queue can be sorted into another queue using a stack
element must be present as a front element of given Queue or top element of the Stack. So,
simply simulate the process for the second Queue by initializing the expected element as 1.
And check if we can get expected element from the front of the given Queue or from the
top of the Stack. If we cannot take it from the either of them then pop the front element of
given Queue and push it in the Stack.
Also, observe, that the stack must also be sorted at each instance i.e the element at the top
of the stack must be smallest in the stack. For eg. let x > y, then x will always be expected
before y. So, x cannot be pushed before y in the stack. Therefore, we cannot push element
with the higher value on the top of the element having lesser value.
Algorithm:
1. Initialize the expected_element = 1
2. Check if either front element of given Queue or top element of the stack have ex-
pected_element
….a) If yes, increment expected_element by 1, repeat step 2.
….b) Else, pop front of Queue and push it to the stack. If the popped element is greater
than top of the Stack, return “No”.
Below is the implementation of this approach:
C++
193
Chapter 37. Check if a queue can be sorted into another queue using a stack
// if top element is less than element which
// need to be pushed, then return fasle.
else if (!st.empty() && st.top() < fnt) {
return false;
}
// else push into the stack.
else
st.push(fnt);
}
// while expected element are coming from
// stack, pop them out.
while (!st.empty() && st.top() == expected) {
st.pop();
expected++;
}
}
// if the final expected element value is equal
// to initial Queue size and the stack is empty.
if (expected - 1 == n && st.empty())
return true;
return false;
}
// Driven Program
int main()
{
queue<int> q;
q.push(5);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
int n = q.size();
(checkSorted(n, q) ? (cout << "Yes") :
(cout << "No"));
return 0;
}
Java
194
Chapter 37. Check if a queue can be sorted into another queue using a stack
195
Chapter 37. Check if a queue can be sorted into another queue using a stack
return false;
}
// else push into the stack.
else
st.push(fnt);
}
// while expected element are
// coming from stack, pop them out.
while (st.size() != 0 &&
st.peek() == expected)
{
st.pop();
expected++;
}
}
// if the final expected element
// value is equal to initial Queue
// size and the stack is empty.
if (expected - 1 == n &&
st.size() == 0)
return true;
return false;
}
// Driver Code
public static void main(String args[])
{
q.add(5);
q.add(1);
q.add(2);
q.add(3);
q.add(4);
int n = q.size();
if (checkSorted(n))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
196
Chapter 37. Check if a queue can be sorted into another queue using a stack
C#
197
Chapter 37. Check if a queue can be sorted into another queue using a stack
return false;
}
// else push into the stack.
else
st.Push(fnt);
}
// while expected element are
// coming from stack, pop them out.
while (st.Count != 0 &&
st.Peek() == expected)
{
st.Pop();
expected++;
}
}
// if the final expected element
// value is equal to initial Queue
// size and the stack is empty.
if (expected - 1 == n &&
st.Count == 0)
return true;
return false;
}
// Driver Code
static void Main()
{
Queue<int> q = new Queue<int>();
q.Enqueue(5);
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Enqueue(4);
int n = q.Count;
if (checkSorted(n, ref q))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
198
Chapter 37. Check if a queue can be sorted into another queue using a stack
Output :
Yes
Source
https://www.geeksforgeeks.org/check-queue-can-sorted-another-queue-using-stack/
199
Chapter 38
Input: arr[] = {{1, 3}, {1, 7}, {4, 8}, {2, 5}}
Output: true
The intervals {1, 3} completely overlaps in {1, 7}.
Input: arr[] = {{1, 3}, {7, 9}, {4, 6}, {10, 13}}
Output: false
No pair of intervals overlap.
A Simple Solution is to consider every pair of intervals and check if the pair overlaps or
not. The time complexity of this solution is O(n2 ).
A better solution is to use Sorting. Following is the complete algorithm.
1) Sort all intervals in increasing order of start time. This step takes O(n Logn) time.
2) In the sorted array, if the end time of an interval is not more than the end of the previous
interval, then there is a complete overlap. This step takes O(n) time.
Given below is an implementation of the above approach:
200
Chapter 38. Check if any interval completely overlaps the other
201
Chapter 38. Check if any interval completely overlaps the other
Output:
Yes
No
Source
https://www.geeksforgeeks.org/check-interval-completely-overlaps/
202
Chapter 39
Check if any two intervals overlap among a given set of intervals - GeeksforGeeks
An interval is represented as a combination of start time and end time. Given a set of
intervals, check if any two intervals overlap.
Input: arr[] = {{1, 3}, {5, 7}, {2, 4}, {6, 8}}
Output: true
The intervals {1, 3} and {2, 4} overlap
Input: arr[] = {{1, 3}, {7, 9}, {4, 6}, {10, 13}}
Output: false
No pair of intervals overlap.
203
Chapter 39. Check if any two intervals overlap among a given set of intervals
204
Chapter 39. Check if any two intervals overlap among a given set of intervals
return 0;
}
Output:
No
Yes
Method 2: This approach is suggested by Anjali Agarwal. Following are the steps:
205
Chapter 39. Check if any two intervals overlap among a given set of intervals
}
// Intialize an array of size max_ele
int aux[max_ele + 1] = { 0 };
for (int i = 0; i < n; i++) {
// starting point of the interval
int x = arr[i].start;
// end point of the interval
int y = arr[i].end;
aux[x]++, aux[y + 1]--;
}
for (int i = 1; i <= max_ele; i++) {
// Calculating the prefix Sum
aux[i] += aux[i - 1];
// Overlap
if (aux[i] > 1)
return true;
}
// If we reach here, then no Overlap
return false;
}
// Driver program
int main()
{
Interval arr1[] = { { 1, 3 }, { 7, 9 }, { 4, 6 }, { 10, 13 } };
int n1 = sizeof(arr1) / sizeof(arr1[0]);
isOverlap(arr1, n1) ? cout << "Yes\n" : cout << "No\n";
Interval arr2[] = { { 6, 8 }, { 1, 3 }, { 2, 4 }, { 4, 7 } };
int n2 = sizeof(arr2) / sizeof(arr2[0]);
isOverlap(arr2, n2) ? cout << "Yes\n" : cout << "No\n";
return 0;
}
// This Code is written by Anjali Agarwal
Output:
No
Yes
206
Chapter 39. Check if any two intervals overlap among a given set of intervals
Note: This method is more efficient than Method 1 if there are more number of intervals and
at the same time maximum value among all intervals should be low, since time complexity
is directly proportional to O(max_ele).
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above
Source
https://www.geeksforgeeks.org/check-if-any-two-intervals-overlap-among-a-given-set-of-intervals/
207
Chapter 40
208
Chapter 40. Check if array contains contiguous integers with duplicates allowed
// integers
#include <bits/stdc++.h>
using namespace std;
// function to check whether
// the array contains a set
// of contiguous integers
bool areElementsContiguous(int arr[], int n)
{
// Sort the array
sort(arr, arr+n);
// After sorting, check if
// current element is either
// same as previous or is
// one more.
for (int i = 1; i < n; i++)
if (arr[i] - arr[i-1] > 1)
return false;
return true;
}
// Driver program to test above
int main()
{
int arr[] = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
if (areElementsContiguous(arr, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
209
Chapter 40. Check if array contains contiguous integers with duplicates allowed
// function to check whether
// the array contains a set
// of contiguous integers
static boolean areElementsContiguous(int arr[],
int n)
{
// Sort the array
Arrays.sort(arr);
// After sorting, check if
// current element is either
// same as previous or is
// one more.
for (int i = 1; i < n; i++)
if (arr[i] - arr[i-1] > 1)
return false;
return true;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = arr.length;
if (areElementsContiguous(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
210
Chapter 40. Check if array contains contiguous integers with duplicates allowed
arr.sort()
# After sorting, check if
# current element is either
# same as previous or is
# one more.
for i in range(1,n):
if (arr[i] - arr[i-1] > 1) :
return 0
return 1
# Driver code
arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]
n = len(arr)
if areElementsContiguous(arr, n): print("Yes")
else: print("No")
# This code is contributed by 'Ansu Kumari'.
C#
211
Chapter 40. Check if array contains contiguous integers with duplicates allowed
// Driver program
public static void Main()
{
int []arr = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = arr.Length;
if (areElementsContiguous(arr, n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by Vt_m.
Output:
Yes
212
Chapter 40. Check if array contains contiguous integers with duplicates allowed
213
Chapter 40. Check if array contains contiguous integers with duplicates allowed
Java
214
Chapter 40. Check if array contains contiguous integers with duplicates allowed
Python3
# Python3 implementation to
# check whether the array
# contains a set of
# contiguous integers
# function to check
# whether the array
# contains a set of
# contiguous integers
def areElementsContiguous(arr, n):
# Find maximum and
# minimum elements.
max1 = max(arr)
min1 = min(arr)
m = max1 - min1 + 1
# There should be at least
# m elements in array to
# make them contiguous.
if (m > n):
215
Chapter 40. Check if array contains contiguous integers with duplicates allowed
return False
# Create a visited array
# and initialize fals
visited = [0] * m
# Mark elements as true.
for i in range(0,n) :
visited[arr[i] - min1] = True
# If any element is not
# marked, all elements
# are not contiguous.
for i in range(0, m):
if (visited[i] == False):
return False
return True
# Driver program
arr = [5, 2, 3, 6, 4, 4, 6, 6 ]
n = len(arr)
if (areElementsContiguous(arr, n)):
print("Yes")
else:
print("No")
# This code is contributed by Smitha Dinesh Semwal
C#
216
Chapter 40. Check if array contains contiguous integers with duplicates allowed
217
Chapter 40. Check if array contains contiguous integers with duplicates allowed
Console.Write("No");
}
}
// This code is contributed by nitin mittal.
Output:
Yes
218
Chapter 40. Check if array contains contiguous integers with duplicates allowed
count++;
// update 'curr_ele"
curr_ele--;
}
// starting with next greater element
// of arr[0]
curr_ele = arr[0] + 1;
// if 'curr_ele' is present in 'us'
while (us.find(curr_ele) != us.end()) {
// increment count
count++;
// update 'curr_ele"
curr_ele++;
}
// returns true if array contains a set of
// contiguous integers else returns false
return (count == (int)(us.size()));
}
// Driver program to test above
int main()
{
int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
if (areElementsContiguous(arr, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
219
Chapter 40. Check if array contains contiguous integers with duplicates allowed
220
Chapter 40. Check if array contains contiguous integers with duplicates allowed
int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };
int n = arr.length;
if (areElementsContiguous(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by 'Gitanjali'.
Python
221
Chapter 40. Check if array contains contiguous integers with duplicates allowed
Output :
Yes
Source
https://www.geeksforgeeks.org/check-array-contains-contiguous-integers-duplicates-allowed/
222
Chapter 41
Check if both halves of the string have at least one different character - GeeksforGeeks
Earlier we have discussed on how to check if both halves of the string have same set of
characters. Now, we further extend our problem on checking if both halves of the string
have at least one different character.
Examples:
Input : baaaab
Output: No, both halves do not differ at all
The two halves contain the same characters
and their frequencies match so not different
the character exists
Input : abccpb
Output : Yes, both halves differ by at least one character
223
Chapter 41. Check if both halves of the string have at least one different character
C++
224
Chapter 41. Check if both halves of the string have at least one different character
Java
225
Chapter 41. Check if both halves of the string have at least one different character
Python3
C#
// C# implementation to check if
226
Chapter 41. Check if both halves of the string have at least one different character
227
Chapter 41. Check if both halves of the string have at least one different character
}
}
//This code is contributed by vt_m.
Output:
C++
228
Chapter 41. Check if both halves of the string have at least one different character
counter[str[i] - 'a']++;
for (int i = l / 2; i < l; i++)
counter[str[i] - 'a']--;
for (int i = 0; i < MAX; i++)
if (counter[i] != 0)
return true;
return false;
}
// Driver function
int main()
{
string str = "abcasdsabcae";
if (function(str))
cout << "Yes, both halves differ"
<<" by at least one character";
else
cout << "No, both halves do"
<<" not differ at all";
return 0;
}
Java
229
Chapter 41. Check if both halves of the string have at least one different character
Python3
230
Chapter 41. Check if both halves of the string have at least one different character
for i in range(MAX):
if (counter[i] != 0):
return True
return False
# Driver function
st = "abcasdsabcae"
if function(st):
print("Yes, both halves differ by at ",
"least one character")
else:
print("No, both halves do not differ at all")
# This code is contributed by Ansu Kumari
C#
231
Chapter 41. Check if both halves of the string have at least one different character
return false;
}
// Driver function
public static void Main()
{
string str = "abcasdsabcae";
if (function(str))
Console.Write("Yes, both halves"
+ " differ by at least one "
+ "character");
else
Console.Write("No, both halves"
+ " do not differ at all");
}
}
// This code is contributed by anuj_67.
232
Chapter 41. Check if both halves of the string have at least one different character
// Declaration and initialization
// of counter array
sort(str, str + (l / 2));
sort(str + (l / 2), str + l);
for (int i = 0; i < l / 2; i++)
if (str[i] != str[l / 2 + i])
return true;
return false;
}
// Driver function
int main()
{
char str[] = "abcasdsabcae";
if (function(str))
cout << "Yes, both halves differ by"
<<" at least one character";
else
cout << "No, both halves do"
<<" not differ at all";
return 0;
}
Java
233
Chapter 41. Check if both halves of the string have at least one different character
Python3
234
Chapter 41. Check if both halves of the string have at least one different character
Source
https://www.geeksforgeeks.org/check-halves-string-least-one-different-character/
235
Chapter 42
Check if given array is almost sorted (elements are at-most one position away) - Geeks-
forGeeks
Given an array with n distinct elements. An array is said to be almost sorted (non-
decreasing) if any of its elements can occurs maximum of 1 distance away from their original
places in sorted array. We need to find whether the given array is almost sorted or not.
Examples:
Sorting Approach : With the help of sorting we can predict whether our given array is
almost sorted or not. Idea behind that is first sort the input array say A[]and then if array
will be almost sorted then each element Ai of given array must be equal to any of Bi-1, Bi
or Bi+1 of sorted array B[].
Time Complexity : O(nlogn)
236
Chapter 42. Check if given array is almost sorted (elements are at-most one position away)
C++
237
Chapter 42. Check if given array is almost sorted (elements are at-most one position away)
// function for checking almost sort
bool almostSort(int A[], int n)
{
// One by one compare adjacents.
for (int i = 0; i < n - 1; i++) {
if (A[i] > A[i + 1]) {
swap(A[i], A[i + 1]);
i++;
}
}
// check whether resultant is sorted or not
for (int i = 0; i < n - 1; i++)
if (A[i] > A[i + 1])
return false;
// is resultant is sorted return true
return true;
}
// driver function
int main()
{
int A[] = { 1, 3, 2, 4, 6, 5 };
int n = sizeof(A) / sizeof(A[0]);
if (almostSort(A, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
238
Chapter 42. Check if given array is almost sorted (elements are at-most one position away)
A[i] = A[i+1];
A[i+1] = temp;
i++;
}
}
// check whether resultant is sorted or not
for (int i = 0; i < n - 1; i++)
if (A[i] > A[i + 1])
return false;
// is resultant is sorted return true
return true;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int A[] = { 1, 3, 2, 4, 6, 5 };
int n = A.length;
if (almostSort(A, n))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by Arnav Kr. Mandal.
C#
239
Chapter 42. Check if given array is almost sorted (elements are at-most one position away)
PHP
<?php
// PHP program to find
// whether given array
// almost sorted or not
// function for checking
// almost sort
function almostSort($A, $n)
{
// One by one compare adjacents.
for ($i = 0; $i < $n - 1; $i++)
{
if ($A[$i] > $A[$i + 1])
{
list($A[$i],
240
Chapter 42. Check if given array is almost sorted (elements are at-most one position away)
Output:
Yes
Source
https://www.geeksforgeeks.org/check-given-array-almost-sorted-elements-one-position-away/
241
Chapter 43
Although the problems looks complex at first look, there is a simple solution to it. If we
traverse array from left to right and we make sure elements before an index i are sorted
before we reach i, we must have maximum of arr[0..i-1] just before i. And this maximum
must be either smaller than arr[i] or just one greater than arr[i]. In first case, we simply
move ahead. In second case, we swap and move ahead.
Compare the current element with the next element in array.If current element is greater
than next element then do following:-
242
Chapter 43. Check if it is possible to sort an array with conditional swapping of adjacent
allowed
Java
class Main
{
243
Chapter 43. Check if it is possible to sort an array with conditional swapping of adjacent
allowed
Python3
# Python 3 program to
# check if we can sort
# an array with adjacent
# swaps allowed
# Returns true if it
# is possible to sort
244
Chapter 43. Check if it is possible to sort an array with conditional swapping of adjacent
allowed
# else false/
def checkForSorting(arr, n):
for i in range(0,n-1):
# We need to do something only if
# previousl element is greater
if (arr[i] > arr[i+1]):
if (arr[i] - arr[i+1] == 1):
arr[i], arr[i+1] = arr[i+1], arr[i]
# If difference is more than
# one, then not possible
else:
return False
return True
# Driver code
arr = [1,0,3,2]
n = len(arr)
if (checkForSorting(arr, n)):
print("Yes")
else:
print("No")
# This code is contributed by
# Smitha Dinesh Semwal
C#
245
Chapter 43. Check if it is possible to sort an array with conditional swapping of adjacent
allowed
PHP
<?php
// PHP program to check if we can sort
// an array with adjacent swaps allowed
// Returns true if it is possible to sort
// else false
function checkForSorting($arr, $n)
{
$temp = 0;
for ($i = 0; $i < $n - 1; $i++)
{
// We need to do something only if
// previousl element is greater
if ($arr[$i] > $arr[$i + 1])
246
Chapter 43. Check if it is possible to sort an array with conditional swapping of adjacent
allowed
{
if ($arr[$i] - $arr[$i + 1] == 1)
{
// swapping
$temp = $arr[$i];
$arr[$i] = $arr[$i + 1];
$arr[$i + 1] = $temp;
}
// If difference is more than
// one, then not possible
else
return false;
}
}
return true;
}
// Driver Code
$arr = array(1,0,3,2);
$n = sizeof($arr);
if (checkForSorting($arr, $n))
echo "Yes";
else
echo "No";
// This code is contributed
// by nitin mittal.
?>
Output:
Yes
Time Complexity=O(n)
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/check-possible-sort-array-conditional-swapping-adjacent-allowed/
247
Chapter 44
Iterative Approach : Traverse the linked list from head to end. For every newly encoun-
tered element, check node -> data > node -> next -> data. If True, do same for each
node else return 0 and Print “No”.
248
Chapter 44. Check if linked list is sorted (Iterative and Recursive)
int data;
struct Node* next;
};
// function to Check Linked List is
// sorted in descending order or not
bool isSortedDesc(struct Node *head)
{
if (head == NULL)
return true;
// Traverse the list till last node and return
// false if a node is smaller than or equal
// its next.
for (Node *t=head; t->next != NULL; t=t->next)
if (t->data <= t->next->data)
return false;
return true;
}
Node *newNode(int data)
{
Node *temp = new Node;
temp->next = NULL;
temp->data = data;
}
// Driver program to test above
int main()
{
struct Node *head = newNode(7);
head->next = newNode(5);
head->next->next = newNode(4);
head->next->next->next = newNode(3);
isSortedDesc(head) ? cout << "Yes" :
cout << "No";
return 0;
}
Output:
Yes
249
Chapter 44. Check if linked list is sorted (Iterative and Recursive)
Recursive Approach :
Check Recursively that node -> data > node -> next -> data, If not, return 0 that
is our terminated condition to come out from recursion else Call Check_List Function
Recursively for next node.
250
Chapter 44. Check if linked list is sorted (Iterative and Recursive)
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-linked-list-sorting-order/
251
Chapter 45
Input : arr [] = { 1, 2, 4, 5, 3 }
Output : No
252
Chapter 45. Check if reversing a sub array make the array sorted
253
Chapter 45. Check if reversing a sub array make the array sorted
checkReverse(arr, n)? (cout << "Yes" << endl):
(cout << "No" << endl);
return 0;
}
Output:
Yes
254
Chapter 45. Check if reversing a sub array make the array sorted
if (j == n)
return true;
// Find last increasing part
int k = j;
// To handle cases like {1,2,3,4,20,9,16,17}
if (arr[k] < arr[i-1])
return false;
while (k > 1 && k < n)
{
if (arr[k] < arr[k-1])
return false;
k++;
}
return true;
}
// Driven Program
int main()
{
int arr[] = {1, 3, 4, 10, 9, 8};
int n = sizeof(arr)/sizeof(arr[0]);
checkReverse(arr, n)? cout << "Yes" : cout << "No";
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-reversing-sub-array-make-array-sorted/
255
Chapter 46
Input : N = 3, M = 2
Edges are:
1) 1-2
2) 2-3
P = {1, 2, 3}
Output : YES
Explanation :
Since there are edges between
1-2 and 2-3, therefore we can
have DFS in the order 1-2-3
Input : N = 3, M = 2
Edges are:
1) 1-2
2) 2-3
P = {1, 3, 2}
Output : NO
Explanation :
Since there is no edge between 1 and 3,
the DFS traversal is not possible
256
Chapter 46. Check if the given permutation is a valid DFS of graph
1. Store the indexes of each number in the given permutation in a Hash map.
2. Sort every adjacency list according to the indexes of permutation since there is need
to maintain the order.
3. Perform the Depth First Traversal Search with source node as 1st number of given
permutation.
4. Keep a counter variable and at every recursive call, check if the counter has reached
the number of nodes, i.e. N and set the flag as 1. If the flag is 0 after complete DFS,
answer is ‘NO’ otherwise ‘YES’
257
Chapter 46. Check if the given permutation is a valid DFS of graph
258
Chapter 46. Check if the given permutation is a valid DFS of graph
// DFS traversal of the
// vertices reachable from v.
void Graph::DFS(int v, int Perm[])
{
// Increment counter for
// every node being traversed
counter++;
// Check if counter has
// reached number of vertices
if (counter == V) {
// Set flag to 1
flag = 1;
return;
}
// Recur for all vertices adjacent
// to this vertices only if it
// lies in the given permutation
list<int>::iterator i;
for (i = adj[v].begin();
i != adj[v].end(); i++)
{
// if the current node equals to
// current element of permutation
if (*i == Perm[counter])
DFS(*i, Perm);
}
}
// Returns true if P[] is a valid DFS of given
// graph. In other words P[] can be obtained by
// doing a DFS of the graph.
bool checkPermutation(int N, int M,
vector<pair<int, int> > V, int P[])
{
// Create the required graph with
// N vertices and M edges
Graph G(N);
// Add Edges to Graph G
for (int i = 0; i < M; i++)
G.addEdge(V[i].first, V[i].second);
for (int i = 0; i < N; i++)
259
Chapter 46. Check if the given permutation is a valid DFS of graph
mp[P[i]] = i;
// Sort every adjacency
// list according to HashMap
for (int i = 1; i <= N; i++)
G.adj[i].sort(cmp);
// Call DFS with source node as P[0]
G.DFS(P[0], P);
// If Flag has been set to 1, means
// given permutation is obtained
// by DFS on given graph
return flag;
}
// Driver code
int main()
{
// Number of vertices and number of edges
int N = 3, M = 2;
// Vector of pair to store edges
vector<pair<int, int> > V;
V.push_back(make_pair(1, 2));
V.push_back(make_pair(2, 3));
int P[] = { 1, 2, 3 };
// Return the answer
if (checkPermutation(N, M, V, P))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
Output:
YES
Source
https://www.geeksforgeeks.org/check-given-permutation-valid-dfs-graph/
260
Chapter 47
Examples :
A simple solution is to sort both array and then linearly compare elements.
C/C++
261
Chapter 47. Check if two arrays are equal or not
Java
262
Chapter 47. Check if two arrays are equal or not
C#
263
Chapter 47. Check if two arrays are equal or not
PHP
<?php
// PHP program to find given
// two array are equal or not
// Returns true if arr1[0..n-1]
// and arr2[0..m-1] contain same elements.
264
Chapter 47. Check if two arrays are equal or not
Output :
Yes
An Efficient solution of this approach is to use hashing. We store all elements of arr1[]
and their counts in a hash table. Then we traverse arr2[] and check if count of every element
in arr2[] matches with count in arr1[].
Below is C++ implementation of above idea. We use unordered_map to store counts.
C/C++
265
Chapter 47. Check if two arrays are equal or not
266
Chapter 47. Check if two arrays are equal or not
Java
267
Chapter 47. Check if two arrays are equal or not
Output :
Yes
268
Chapter 47. Check if two arrays are equal or not
Source
https://www.geeksforgeeks.org/check-if-two-arrays-are-equal-or-not/
269
Chapter 48
Check whether Arithmetic Progression can be formed from the given array - GeeksforGeeks
Given an array of n integers. The task is to check whether an arithmetic progression can
be formed using all the given elements. If possible print “Yes”, else print “No”.
Examples:
Method 1 (Simple)
A simple solution is to first find the smallest element, then find second smallest element and
find the difference between these two. Let this difference be d. After finding the difference,
find third smallest, fourth smallest and so on. After finding every i-th smallest smallest (from
third onward), find the difference between value of current element and value of previous
element. If difference is not same as d, return false. If all elements have same difference,
return true. Time complexity of this solution is O(n2 )
Method 2(Use Sorting)
The idea is to sort the given array. After sorting, check if differences between consecutive
elements are same or not. If all differences are same, Arithmetic Progression is possible.
270
Chapter 48. Check whether Arithmetic Progression can be formed from the given array
Java
271
Chapter 48. Check whether Arithmetic Progression can be formed from the given array
// Returns true if a permutation of
// arr[0..n-1] can form arithmetic
// progression
static boolean checkIsAP(int arr[], int n)
{
if (n == 1)
return true;
// Sort array
Arrays.sort(arr);
// After sorting, difference between
// consecutive elements must be same.
int d = arr[1] - arr[0];
for (int i = 2; i < n; i++)
if (arr[i] - arr[i-1] != d)
return false;
return true;
}
//driver code
public static void main (String[] args)
{
int arr[] = { 20, 15, 5, 0, 10 };
int n = arr.length;
if(checkIsAP(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Anant Agarwal.
Python3
272
Chapter 48. Check whether Arithmetic Progression can be formed from the given array
arr.sort()
# After sorting, difference between
# consecutive elements must be same.
d = arr[1] - arr[0]
for i in range(2, n):
if (arr[i] - arr[i-1] != d):
return False
return True
# Driver code
arr = [ 20, 15, 5, 0, 10 ]
n = len(arr)
print("Yes") if(checkIsAP(arr, n)) else print("No")
# This code is contributed by Anant Agarwal.
C#
273
Chapter 48. Check whether Arithmetic Progression can be formed from the given array
PHP
<?php
// PHP program to check if
// a given array can form
// arithmetic progression
// Returns true if a permutation
// of arr[0..n-1] can form
// arithmetic progression
function checkIsAP($arr, $n)
{
if ($n == 1)
return true;
// Sort array
sort($arr);
// After sorting, difference
// between consecutive elements
// must be same.
$d = $arr[1] - $arr[0];
for ($i = 2; $i < $n; $i++)
if ($arr[$i] -
$arr[$i - 1] != $d)
return false;
return true;
}
// Driver Code
$arr = array(20, 15, 5, 0, 10);
$n = count($arr);
274
Chapter 48. Check whether Arithmetic Progression can be formed from the given array
if(checkIsAP($arr, $n))
echo "Yes";
else
echo "No";
// This code is contributed
// by Sam007
?>
Output:
Yes
275
Chapter 48. Check whether Arithmetic Progression can be formed from the given array
Source
https://www.geeksforgeeks.org/check-whether-arithmetic-progression-can-formed-given-array/
276
Chapter 49
277
Chapter 49. Check whether a given array is a k sorted array or not
278
Chapter 49. Check whether a given array is a k sorted array or not
// 'arr' is a k sorted array
return "Yes";
}
// Driver program to test above
int main()
{
int arr[] = {3, 2, 1, 5, 6, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
cout << "Is it a k sorted array?: "
<< isKSortedArray(arr, n, k);
return 0;
}
Java
279
Chapter 49. Check whether a given array is a k sorted array or not
C#
// C# implementation to check
// whether the given array is a
// k sorted array or not
using System;
using System.Collections;
class GFG {
// Method to check whether the given
// array is a 'k' sorted array or not
static String isKSortedArray(int []arr, int n, int k)
{
// auxiliary array 'aux'
int []aux = new int[n];
// copy elements of 'arr' to 'aux'
for (int i = 0; i<n; i++)
aux[i] = arr[i];
// sort 'aux'
Array.Sort(aux);
// for every element of 'arr' at index
// 'i', find its index 'j' in 'aux'
for (int i = 0; i<n; i++)
280
Chapter 49. Check whether a given array is a k sorted array or not
{
// index of arr[i] in sorted array 'aux'
int j = Array.BinarySearch(aux,arr[i]);
// if abs(i-j) > k, then that element is
// not at-most k distance away from its
// target position. Thus, 'arr' is not a
// k sorted array
if (Math.Abs(i - j) > k)
return "No";
}
// 'arr' is a k sorted array
return "Yes";
}
// Driver method
public static void Main()
{
int []arr = {3, 2, 1, 5, 6, 4};
int k = 2;
Console.WriteLine("Is it a k sorted array ?: " +
isKSortedArray(arr, arr.Length, k));
}
}
// This code is contributed by Sam007
Output:
Source
https://www.geeksforgeeks.org/check-whether-given-array-k-sorted-array-not/
281
Chapter 50
Examples :
282
Chapter 50. Check whether a given number is even or odd
input: 2
output: even
input: 5
output: odd
Java
283
Chapter 50. Check whether a given number is even or odd
int n = 101;
if(isEven(n) == true)
System.out.print("Even");
else
System.out.print("Odd");
}
}
// This code is contributed by rishabh_jain
Python3
C#
284
Chapter 50. Check whether a given number is even or odd
}
}
// This code is contributed by vt_m
PHP
<?php
// A simple PHP program to
// check for even or odd
// Returns true if n is
// even, else odd
function isEven($n)
{
return ($n % 2 == 0);
}
// Driver code
$n = 101;
if(isEven != true)
echo "Even";
else
echo "Odd";
// This code is contributed by Ajit
?>
Output :
Odd
A better solution is to use bitwise operators. We need to check whether last bit is 1 or
not. If last bit is 1 then number is odd, otherwise always even.
Explanation:
input : 5 // odd
00000101
& 00000001
--------------
00000001
--------------
input : 8 //even
285
Chapter 50. Check whether a given number is even or odd
00001000
& 00000001
--------------
00000000
--------------
Java
286
Chapter 50. Check whether a given number is even or odd
else
return false;
}
// Driver code
public static void main(String[] args)
{
int n = 101;
if(isEven(n) == true)
System.out.print("Even");
else
System.out.print("Odd");
}
}
// This code is contributed by rishabh_jain
Python3
C#
287
Chapter 50. Check whether a given number is even or odd
return true;
else
return false;
}
// Driver code
public static void Main()
{
int n = 101;
if(isEven(n) == true)
Console.WriteLine("Even");
else
Console.WriteLine("Odd");
}
}
// This code is contributed by vt_m.
PHP
<?php
// A simple PHP program to
// check for even or odd
// Returns true if n is
// even, else odd
function isEven($n)
{
return (!($n & 1));
}
// Driver code
$n = 101;
if(isEven($n) == true)
echo "Even";
else
echo "Odd";
// This code is contributed by Smitha
?>
Output :
Odd
288
Chapter 50. Check whether a given number is even or odd
Source
https://www.geeksforgeeks.org/check-whether-given-number-even-odd/
289
Chapter 51
Check whether an array can be fit into another array rearranging the elements in the array
- GeeksforGeeks
Given two arrays A and B of same size N. Check whether array A can be fit into array
B. An array is said to fit into another array if by arranging the elements of both arrays,
there exists a solution such that the ith element of the first array is less than or equal to ith
element of the second array.
Examples:
Approach : Sort both the arrays and check whether Ai is less than or equal to Bi for all 0
� i � N. If at any ith position Ai is greater than Bi return false, otherwise return true.
Below is the implementation of the above approach:
C++
290
Chapter 51. Check whether an array can be fit into another array rearranging the elements
in the array
Java
291
Chapter 51. Check whether an array can be fit into another array rearranging the elements
in the array
class GFG
{
// Returns true if the
// array A can be fit
// into array B,
// otherwise false
static boolean checkFittingArrays(int []A,
int []B,
int N)
{
// Sort both the arrays
Arrays.sort(A);
Arrays.sort(B);
// Iterate over the loop
// and check whether every
// array element of A is
// less than or equal to
// its corresponding array
// element of B
for (int i = 0; i < N; i++)
if (A[i] > B[i])
return false;
return true;
}
// Driver Code
public static void main(String[] args)
{
int A[] = {7, 5, 3, 2};
int B[] = {5, 4, 8, 7};
int N = A.length;
if (checkFittingArrays(A, B, N))
System.out.print("YES");
else
System.out.print("NO");
}
}
C#
// C# Program to check
// whether an array can
// be fit into another
292
Chapter 51. Check whether an array can be fit into another array rearranging the elements
in the array
293
Chapter 51. Check whether an array can be fit into another array rearranging the elements
in the array
// by anuj_67.
Output:
YES
Source
https://www.geeksforgeeks.org/check-whether-an-array-can-be-fit-into-another-array-rearranging-the-elements-in-t
294
Chapter 52
Examples:
295
Chapter 52. Chocolate Distribution Problem
m = 7
Output: Minimum Difference is 10
We need to pick 7 packets. We pick 40, 41,
42, 44, 48, 43 and 50 to minimize difference
between maximum and minimum.
296
Chapter 52. Chocolate Distribution Problem
Java
297
Chapter 52. Chocolate Distribution Problem
Arrays.sort(arr);
// Number of students cannot be
// more than number of packets
if (n < m)
return -1;
// Largest number of chocolates
int min_diff = Integer.MAX_VALUE;
// Find the subarray of size m
// such that difference between
// last (maximum in case of
// sorted) and first (minimum in
// case of sorted) elements of
// subarray is minimum.
int first = 0, last = 0;
for (int i = 0; i + m - 1 < n; i++)
{
int diff = arr[i+m-1] - arr[i];
if (diff < min_diff)
{
min_diff = diff;
first = i;
last = i + m - 1;
}
}
return (arr[last] - arr[first]);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {12, 4, 7, 9, 2, 23,
25, 41, 30, 40, 28,
42, 30, 44, 48, 43,
50};
int m = 7; // Number of students
int n = arr.length;
System.out.println("Minimum difference is "
+ findMinDiff(arr, n, m));
}
}
// This code is contributed by Arnav Kr. Mandal.
298
Chapter 52. Chocolate Distribution Problem
Python3
299
Chapter 52. Chocolate Distribution Problem
C#
300
Chapter 52. Chocolate Distribution Problem
PHP
<?php
// PHP program to solve
// chocolate distribution
// problem
// arr[0..n-1] represents
301
Chapter 52. Chocolate Distribution Problem
// sizes of packets m is
// number of students.
// Returns minimum difference
// between maximum and minimum
// values of distribution.
function findMinDiff($arr, $n, $m)
{
// if there are no
// chocolates or number
// of students is 0
if ($m == 0 || $n == 0)
return 0;
// Sort the given packets
sort($arr);
// Number of students
// cannot be more than
// number of packets
if ($n < $m)
return -1;
// Largest number
// of chocolates
$min_diff = PHP_INT_MAX;
// Find the subarray of size
// m such that difference
// between last (maximum in
// case of sorted) and first
// (minimum in case of sorted)
// elements of subarray is minimum.
$first = 0; $last = 0;
for ($i = 0;
$i + $m - 1 < $n; $i++)
{
$diff = $arr[$i + $m - 1] -
$arr[$i];
if ($diff < $min_diff)
{
$min_diff = $diff;
$first = $i;
$last = $i + $m - 1;
}
}
return ($arr[$last] -
$arr[$first]);
}
302
Chapter 52. Chocolate Distribution Problem
// Driver Code
$arr = array(12, 4, 7, 9, 2, 23,
25, 41, 30, 40, 28,
42, 30, 44, 48, 43, 50);
$m = 7; // Number of students
$n = sizeof($arr);
echo "Minimum difference is ",
findMinDiff($arr, $n, $m);
// This code is contributed by ajit
?>
Output:
Minimum difference is 10
Source
https://www.geeksforgeeks.org/chocolate-distribution-problem/
303
Chapter 53
Choose k array elements such that difference of maximum and minimum is minimized -
GeeksforGeeks
Given an array of n integers and a positive number k. We are allowed to take any k integers
from the given array. The task is to find the minimum possible value of the difference
between maximum and minimum of K numbers.
Examples:
The idea is to sort the array and choose k continuous integers. Why continuous? let the
chosen k integers be arr[0], arr[1]„..arr[r], arr[r+x]…, arr[k-1], all in increasing order but not
continuous in the sorted array. This means there exists an integer p which lies between
304
Chapter 53. Choose k array elements such that difference of maximum and minimum is
minimized
arr[r] and arr[r+x],. So if p is included and arr[0] is removed, then the new difference will be
arr[r] – arr[1] whereas old difference was arr[r] – arr[0]. And we know arr[0] <= arr[1] <=
..<= arr[k-1] so minimum difference reduces or remain same. If we perform same procedure
for other p like number, we get the minimum difference.
Algorithm to solve the problem:
305
Chapter 53. Choose k array elements such that difference of maximum and minimum is
minimized
Java
Python3
306
Chapter 53. Choose k array elements such that difference of maximum and minimum is
minimized
result = +2147483647
# Sorting the array.
arr.sort()
# Find minimum value among
# all K size subarray.
for i in range(n-k+1):
result = int(min(result, arr[i+k-1] - arr[i]))
return result
# Driver code
arr= [10, 100, 300, 200, 1000, 20, 30]
n =len(arr)
k = 3
print(minDiff(arr, n, k))
# This code is contributed
# by Anant Agarwal.
C#
307
Chapter 53. Choose k array elements such that difference of maximum and minimum is
minimized
return result;
}
// Driver code
public static void Main() {
int []arr = {10, 100, 300, 200, 1000, 20, 30};
int n = arr.Length;
int k = 3;
Console.WriteLine(minDiff(arr, n, k));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find minimum
// difference of maximum and
// minimum of K number.
// Return minimum difference
// of maximum and minimum
// of k elements of arr[0..n-1].
function minDiff($arr, $n, $k)
{
$INT_MAX = 2147483647;
$result = $INT_MAX ;
// Sorting the array.
sort($arr , $n);
sort($arr);
// Find minimum value among
// all K size subarray.
for ($i = 0; $i <= $n - $k; $i++)
$result = min($result, $arr[$i + $k - 1] -
$arr[$i]);
return $result;
}
// Driver Code
$arr = array(10, 100, 300, 200, 1000, 20, 30);
$n = sizeof($arr);
$k = 3;
echo minDiff($arr, $n, $k);
308
Chapter 53. Choose k array elements such that difference of maximum and minimum is
minimized
Output:
20
Source
https://www.geeksforgeeks.org/k-numbers-difference-maximum-minimum-k-number-minimized/
309
Chapter 54
Circle Sort
• Compare the first element to the last element, then the second element to the second
last element, etc.
• Then split the array in two and recurse until there is only one single element in the
array.
310
Chapter 54. Circle Sort
311
Chapter 54. Circle Sort
312
Chapter 54. Circle Sort
Output :
Unsorted : [6, 5, 3, 1, 8, 7, 2, 4]
Sorted : [1, 2, 3, 4, 5, 6, 7, 8]
References :
SourceForge
Source
https://www.geeksforgeeks.org/circle-sort/
313
Chapter 55
This problem is mainly an extension ofFind minimum difference between any two elements.
C++
314
Chapter 55. Closest numbers from a list of unsorted integers
// Returns minimum difference between any
// two pair in arr[0..n-1]
void printMinDiffPairs(int arr[], int n)
{
if (n <= 1)
return;
// Sort array elements
sort(arr, arr+n);
// Compare differences of adjacent
// pairs to find the minimum difference.
int minDiff = arr[1] - arr[0];
for (int i = 2 ; i < n ; i++)
minDiff = min(minDiff, arr[i] - arr[i-1]);
// Traverse array again and print all pairs
// with difference as minDiff.
for (int i = 1; i < n; i++)
if ((arr[i] - arr[i-1]) == minDiff)
cout << "(" << arr[i-1] << ", "
<< arr[i] << "), ";
}
// Driver code
int main()
{
int arr[] = {5, 3, 2, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printMinDiffPairs(arr, n);
return 0;
}
Java
315
Chapter 55. Closest numbers from a list of unsorted integers
return;
// Sort array elements
Arrays.sort(arr);
// Compare differences of adjacent
// pairs to find the minimum difference.
int minDiff = arr[1] - arr[0];
for (int i = 2; i < n; i++)
minDiff = Math.min(minDiff, arr[i] - arr[i-1]);
// Traverse array again and print all pairs
// with difference as minDiff.
for ( int i = 1; i < n; i++)
{
if ((arr[i] - arr[i-1]) == minDiff)
{
System.out.print("(" + arr[i-1] + ", "
+ arr[i] + ")," );
}
}
}
// Driver code
public static void main (String[] args)
{
int arr[] = {5, 3, 2, 4, 1};
int n = arr.length;
printMinDiffPairs(arr, n);
}
}
// This code is contributed by Ansu Kumari
Python3
316
Chapter 55. Closest numbers from a list of unsorted integers
C#
317
Chapter 55. Closest numbers from a list of unsorted integers
PHP
<?php
//PHP program to find minimum difference
// an unsorted array.
// Returns minimum difference between any
// two pair in arr[0..n-1]
function printMinDiffPairs($arr, $n)
{
if ($n <= 1)
return;
// Sort array elements
sort($arr);
// Compare differences of adjacent
// pairs to find the minimum
// difference.
$minDiff = $arr[1] - $arr[0];
for ($i = 2 ; $i < $n ; $i++)
$minDiff = min($minDiff, $arr[$i]
- $arr[$i-1]);
// Traverse array again and print all
// pairs with difference as minDiff.
for ($i = 1; $i < $n; $i++)
if (($arr[$i] - $arr[$i-1]) ==
318
Chapter 55. Closest numbers from a list of unsorted integers
$minDiff)
echo "(" , $arr[$i-1] , ", ",
$arr[$i] , "), ";
}
// Driver code
$arr = array(5, 3, 2, 4, 1);
$n = sizeof($arr);
printMinDiffPairs($arr, $n);
// This code is contributed by ajit.
?>
Output:
Source
https://www.geeksforgeeks.org/closest-numbers-list-unsorted-integers/
319
Chapter 56
Method 1
A simple solution is to consider every pair and keep track of closest pair (absolute difference
between pair product and x is minimum). Finally print the closest pair. Time complexity
of this solution is O( )
Method 2 O(n Log n)
2. Initialize a variable diff as infinite (Diff is used to store the difference between pair
and x). We need to find the minimum diff.
3. Traverse the array and for each i, do the following :
• Find the lower bound for x/arr[i] in the sub array on right of arr[i], i.e., in sub
array arr[i+1..n-1]. Let it be denoted be l.
320
Chapter 56. Closest product pair in an array
• Find the upper bound for x/arr[i] in the sub array on right of arr[i], i.e., in sub
array arr[i+1..n-1]. Let it be denoted be u.
• If min(abs((arr[i] * l) – x), abs((arr[i] * u) – x)) < diff then update diff and result
321
Chapter 56. Closest product pair in an array
Java
322
Chapter 56. Closest product pair in an array
Python3
323
Chapter 56. Closest product pair in an array
# to a given no.
import sys
# Prints the pair with
# product closest to x
def printClosest(arr, n, x):
# To store indexes
# of result pair
res_l = 0;
res_r = 0;
# Initialize left and right
# indexes and difference
# between pair product and x
l = 0;
r = n - 1;
diff = sys.maxsize;
# While there are elements
# between l and r
while (r > l):
# Check if this pair is
# closer than the closest
# pair so far
if (abs(arr[l] *
arr[r] - x) < diff):
res_l = l;
res_r = r;
diff = abs(arr[l] *
arr[r] - x);
# If this pair has more
# product, move to smaller
# values.
if (arr[l] * arr[r] > x):
r = r - 1;
# Move to larger values
else:
l = l + 1;
print("The closest pair is", arr[res_l] ,
"and", arr[res_r]);
# Driver Code
arr = [2, 3, 5, 9];
324
Chapter 56. Closest product pair in an array
x = 8;
n = len(arr);
printClosest(arr, n, x);
# This code is contributed
# by rahul
C#
325
Chapter 56. Closest product pair in an array
PHP
<?php
// Simple PHP program to find
// the pair with product closest
// to a given no.
// Prints the pair with
// product closest to x
function printClosest($arr, $n, $x)
{
// To store indexes
// of result pair
$res_l; $res_r;
// Initialize left and right
// indexes and difference
// between pair product and x
$l = 0; $r = $n - 1; $diff = PHP_INT_MAX;
// While there are elements
// between l and r
326
Chapter 56. Closest product pair in an array
Output :
327
Chapter 56. Closest product pair in an array
Source
https://www.geeksforgeeks.org/closest-product-pair-array/
328
Chapter 57
Cocktail Sort
Algorithm:
Each iteration of the algorithm is broken up into 2 stages:
1. The first stage loops through the array from left to right, just like the Bubble Sort.
During the loop, adjacent items are compared and if value on the left is greater than
the value on the right, then values are swapped. At the end of first iteration, largest
number will reside at the end of the array.
2. The second stage loops through the array in opposite direction- starting from the item
just before the most recently sorted item, and moving back to the start of the array.
Here also, adjacent items are compared and are swapped if required.
329
Chapter 57. Cocktail Sort
330
Chapter 57. Cocktail Sort
// if nothing moved, then array is sorted.
if (!swapped)
break;
// otherwise, reset the swapped flag so that it
// can be used in the next stage
swapped = false;
// move the end point back by one, because
// item at the end is in its rightful spot
--end;
// from right to left, doing the
// same comparison as in the previous stage
for (int i = end - 1; i >= start; --i) {
if (a[i] > a[i + 1]) {
swap(a[i], a[i + 1]);
swapped = true;
}
}
// increase the starting point, because
// the last stage would have moved the next
// smallest number to its rightful spot.
++start;
}
}
/* Prints the array */
void printArray(int a[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
// Driver code
int main()
{
int arr[] = { 5, 1, 4, 2, 8, 0, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
CocktailSort(a, n);
printf("Sorted array :\n");
printArray(a, n);
return 0;
}
331
Chapter 57. Cocktail Sort
Java
332
Chapter 57. Cocktail Sort
}
// increase the starting point, because
// the last stage would have moved the next
// smallest number to its rightful spot.
start = start + 1;
}
}
/* Prints the array */
void printArray(int a[])
{
int n = a.length;
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
}
// Driver method
public static void main(String[] args)
{
CocktailSort ob = new CocktailSort();
int a[] = { 5, 1, 4, 2, 8, 0, 2 };
ob.cocktailSort(a);
System.out.println("Sorted array");
ob.printArray(a);
}
}
Python
333
Chapter 57. Cocktail Sort
C#
334
Chapter 57. Cocktail Sort
335
Chapter 57. Cocktail Sort
Output:
• https://en.wikipedia.org/wiki/Cocktail_shaker_sort
• http://will.thimbleby.net/algorithms/doku.php?id=cocktail_sort
• http://www.programming-algorithms.net/article/40270/Shaker-sort
Improved By : Sam007
336
Chapter 57. Cocktail Sort
Source
https://www.geeksforgeeks.org/cocktail-sort/
337
Chapter 58
Comb Sort
338
Chapter 58. Comb Sort
{
// Initialize gap
int gap = n;
// Initialize swapped as true to make sure that
// loop runs
bool swapped = true;
// Keep running while gap is more than 1 and last
// iteration caused a swap
while (gap != 1 || swapped == true)
{
// Find next gap
gap = getNextGap(gap);
// Initialize swapped as false so that we can
// check if swap happened or not
swapped = false;
// Compare all elements with current gap
for (int i=0; i<n-gap; i++)
{
if (a[i] > a[i+gap])
{
swap(a[i], a[i+gap]);
swapped = true;
}
}
}
}
// Driver program
int main()
{
int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
int n = sizeof(a)/sizeof(a[0]);
combSort(a, n);
printf("Sorted array: \n");
for (int i=0; i<n; i++)
printf("%d ", a[i]);
return 0;
}
Java
339
Chapter 58. Comb Sort
340
Chapter 58. Comb Sort
}
}
}
}
// Driver method
public static void main(String args[])
{
CombSort ob = new CombSort();
int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
ob.sort(arr);
System.out.println("sorted array");
for (int i=0; i<arr.length; ++i)
System.out.print(arr[i] + " ");
}
}
/* This code is contributed by Rajat Mishra */
Python
341
Chapter 58. Comb Sort
C#
342
Chapter 58. Comb Sort
int gap = n;
// Initialize swapped as true to
// make sure that loop runs
bool swapped = true;
// Keep running while gap is more than
// 1 and last iteration caused a swap
while (gap != 1 || swapped == true)
{
// Find next gap
gap = getNextGap(gap);
// Initialize swapped as false so that we can
// check if swap happened or not
swapped = false;
// Compare all elements with current gap
for (int i=0; i<n-gap; i++)
{
if (arr[i] > arr[i+gap])
{
// Swap arr[i] and arr[i+gap]
int temp = arr[i];
arr[i] = arr[i+gap];
arr[i+gap] = temp;
// Set swapped
swapped = true;
}
}
}
}
// Driver method
public static void Main()
{
int []arr = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
sort(arr);
Console.WriteLine("sorted array");
for (int i=0; i<arr.Length; ++i)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Sam007
343
Chapter 58. Comb Sort
Output :
Sorted array:
-44 -6 0 1 3 4 8 23 28 56
Illustration:
Let the array elements be
8 4 1 56 3 -44 23 -6 28 0
-6 4 1 56 3 -44 23 8 28 0
-6 4 0 56 3 -44 23 8 28 1
-44 4 0 56 3 -6 23 8 28 1
-44 4 0 28 3 -6 23 8 56 1
-44 4 0 28 1 -6 23 8 56 3
-44 1 0 28 4 -6 23 8 56 3
-44 1 -6 28 4 0 23 8 56 3
-44 1 -6 23 4 0 28 8 56 3
-44 1 -6 23 4 0 3 8 56 28
-44 1 -6 0 4 23 3 8 56 28
-44 1 -6 0 3 23 4 8 56 28
-44 1 -6 0 3 8 4 23 56 28
-44 -6 1 0 3 8 4 23 56 28
-44 -6 0 1 3 8 4 23 56 28
-44 -6 0 1 3 4 8 23 56 28
-44 -6 0 1 3 4 8 23 28 56
344
Chapter 58. Comb Sort
Time Complexity : Worst case complexity of this algorithm is O(n2 ) and the Best Case
complexity is O(n).
Auxiliary Space : O(1).
Snapshots:
345
Chapter 58. Comb Sort
346
Chapter 58. Comb Sort
347
Chapter 58. Comb Sort
348
Chapter 58. Comb Sort
349
Chapter 58. Comb Sort
350
Chapter 58. Comb Sort
351
Chapter 58. Comb Sort
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Improved By : Sam007
Source
https://www.geeksforgeeks.org/comb-sort/
352
Chapter 59
The key point about qsort() is comparator function comparator. The comparator function
takes two arguments and contains logic to decide their relative order in sorted output. The
idea is to provide flexibility so that qsort() can be used for any type (including user defined
types) and can be used to obtain any desired order (increasing, decreasing or any other).
The comparator function takes two pointers as arguments (both type-casted to const void*)
and defines the order of the elements by returning (in a stable and transitive manner
Source: http://www.cplusplus.com/reference/cstdlib/qsort/
For example, let there be an array of students where following is type of student.
struct Student
353
Chapter 59. Comparator function of qsort() in C
{
int age, marks;
char name[20];
};
Lets say we need to sort the students based on marks in ascending order. The comparator
function will look like:
#include <stdio.h>
#include <stdlib.h>
// This function is used in qsort to decide the relative order
// of elements at addresses p and q.
int comparator(const void *p, const void *q)
{
// Get the values at given addresses
int l = *(const int *)p;
354
Chapter 59. Comparator function of qsort() in C
Output:
Output array is
9 7 5 3 1 2 4 6 8
Exercise:
Given an array of integers, sort it in alternate fashion. Alternate fashion means that the
355
Chapter 59. Comparator function of qsort() in C
elements at even indices are sorted separately and elements at odd indices are sorted sepa-
rately.
This article is compiled by Aashish Barnwal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/comparator-function-of-qsort-in-c/
356
Chapter 60
Comparisons involved in
Modified Quicksort Using
Merge Sort Tree
If we carefully analyze the quick sort algorithm then every time the array is given to the
quick sort function, the array always consists of a permutation of the numbers in some range
L to R. Initially, it’s [1 to N], then its [1 to pivot – 1] and [pivot + 1 to N] and so on. Also
it’s not easy to observe that the relative ordering of numbers in every possible array does
not change. Now in order to get the pivot element we just need to get the middle number
i.e the (r – l + 2)/2th number among the array.
To do this efficiently we can use a Persistent Segment Tree, a Fenwick Tree, or a Merge Sort
Tree. This Article focuses on the Merge Sort Tree Implementation.
In the Modified Quick Sort Algorithm where we chose the pivot element of the array as the
median of the array. Now, determining the median requires us to find the middle element
considered, after sorting the array which is in itself a O(n*log(n)) operation where n is the
size of the array.
357
Chapter 60. Comparisons involved in Modified Quicksort Using Merge Sort Tree
Let’s say we have a range L to R then the median of this range is calculated as:
Let’s consider we have P partitions during the quick sort algorithm which means we have
to find the pivot by sorting the array range from L to R where L and R are the starting and
ending points of each partition. This is costly.
But, we have a permutation of numbers from L to R in every partition, so we can just find
the ceil((R – L + 1)/2)th smallest number in this range as we know when we would have
sorted this partition then it would always would have been this element that would have
ended up as being the median element as a result also the pivot. Now the elements less
than pivot go to the left subtree and the ones greater than it go in the right subtree also
mantaining their order.
We repeat this procedure for all partitions P and find the comparisons involved in each
partition. Since in the Current Partition all the elements from L to R of that partition
are compared to the pivot, we have (R – L + 1) comparisons in the current partition. We
also need to consider, by recursively calculating, the total comparisons in the left and right
subtrees formed too. Thus we conclude,
We discussed above the approach to be used to find the pivot element efficiently here the
Kth order statistics using merge sort tree can be used to find the same as discussed.
358
Chapter 60. Comparisons involved in Modified Quicksort Using Merge Sort Tree
359
Chapter 60. Comparisons involved in Modified Quicksort Using Merge Sort Tree
int first_in_query_range =
(lower_bound(tree[2 * treeIndex].begin(),
tree[2 * treeIndex].end(), queryStart)
- tree[2 * treeIndex].begin());
int M = last_in_query_range - first_in_query_range;
if (M >= K) {
// Kth smallest is in left subtree,
// so recursively call left subtree for Kth
// smallest number
return queryRec(segmentStart, mid, queryStart,
queryEnd, 2 * treeIndex, K, tree);
}
else {
// Kth smallest is in right subtree,
// so recursively call right subtree for the
// (K-M)th smallest number
return queryRec(mid + 1, segmentEnd, queryStart,
queryEnd, 2 * treeIndex + 1, K - M, tree);
}
}
// A wrapper over query()
int query(int queryStart, int queryEnd, int K, int n, int arr[],
vector<int> tree[])
{
return queryRec(1, n, queryStart, queryEnd,
1, K, tree);
}
/* Calculates total Comparisons Involved in Quick Sort
Has the following parameters:
start => starting index of array
end => ending index of array
n => size of array
tree => Merge Sort Tree */
int quickSortComparisons(int start, int end, int n, int arr[],
vector<int> tree[])
{
/* Base Case */
if (start >= end)
360
Chapter 60. Comparisons involved in Modified Quicksort Using Merge Sort Tree
return 0;
// Compute the middle point of range and the pivot
int middlePoint = (end - start + 2) / 2;
int pivot = query(start, end, middlePoint, n, arr, tree);
/* Total Comparisons = (Comparisons in Left part +
Comparisons of right +
Comparisons in parent) */
// count comparisons in parent array
int comparisons_in_parent = (end - start + 1);
// count comparisons involved in left partition
int comparisons_in_left_part =
quickSortComparisons(start, pivot - 1, n, arr, tree);
// count comparisons involved in right partition
int comparisons_in_right_part =
quickSortComparisons(pivot + 1, end, n, arr, tree);
// Return Total Comparisons
return comparisons_in_left_part +
comparisons_in_parent +
comparisons_in_right_part;
}
// Driver code
int main()
{
int arr[] = { 4, 3, 5, 1, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
// Construct segment tree in tree[]
vector<int> tree[MAX];
buildTree(1, 1, n, arr, tree);
cout << "Number of Comparisons = "
<< quickSortComparisons(1, n, n, arr, tree);;
return 0;
}
Output:
Number of Comparisons = 11
361
Chapter 60. Comparisons involved in Modified Quicksort Using Merge Sort Tree
Source
https://www.geeksforgeeks.org/comparisons-involved-modified-quicksort-using-merge-sort-tree/
362
Chapter 61
363
Chapter 61. Convert an array to reduced form Set 1 (Simple and Hashing)
5) Traverse given array and change elements to their positions using hash table. This takes
O(n) time on average.
Overall time complexity of this solution is O(n Log n).
Below are implementations of above idea.
C++
364
Chapter 61. Convert an array to reduced form Set 1 (Simple and Hashing)
{
int arr[] = {10, 20, 15, 12, 11, 50};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Given Array is \n";
printArr(arr, n);
convert(arr , n);
cout << "\n\nConverted Array is \n";
printArr(arr, n);
return 0;
}
Java
365
Chapter 61. Convert an array to reduced form Set 1 (Simple and Hashing)
Python3
366
Chapter 61. Convert an array to reduced form Set 1 (Simple and Hashing)
val += 1
# Convert array by taking positions from umap
for i in range (n):
arr[i] = umap[arr[i]]
def printArr(arr, n):
for i in range(n):
print(arr[i], end = " ")
# Driver Code
if __name__ == "__main__":
arr = [10, 20, 15, 12, 11, 50]
n = len(arr)
print("Given Array is ")
printArr(arr, n)
convert(arr , n)
print("\n\nConverted Array is ")
printArr(arr, n)
# This code is contributed by Abhishek Gupta
Output :
Given Array is
10 20 15 12 11 50
Converted Array is
0 4 3 2 1 5
Source
https://www.geeksforgeeks.org/convert-an-array-to-reduced-form-set-1-simple-and-hashing/
367
Chapter 62
368
Chapter 62. Convert an array to reduced form Set 2 (Using vector of pairs)
Output :
Given Array is
10 20 15 12 11 50
Converted Array is
369
Chapter 62. Convert an array to reduced form Set 2 (Using vector of pairs)
0 4 3 2 1 5
Source
https://www.geeksforgeeks.org/convert-array-reduced-form-set-2-using-vector-pairs/
370
Chapter 63
METHOD 1 (Simple)
For each element, count number of elements which are on right side of it and are smaller
than it.
C
#include <bits/stdc++.h>
int getInvCount(int arr[], int n)
{
int inv_count = 0;
for (int i = 0; i < n - 1; i++)
for (int j = i+1; j < n; j++)
if (arr[i] > arr[j])
inv_count++;
return inv_count;
}
/* Driver progra to test above functions */
int main(int argv, char** args)
371
Chapter 63. Count Inversions in an array Set 1 (Using Merge Sort)
{
int arr[] = {1, 20, 6, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
printf(" Number of inversions are %d \n", getInvCount(arr, n));
return 0;
}
Java
Python3
372
Chapter 63. Count Inversions in an array Set 1 (Using Merge Sort)
return inv_count
# Driver Code
arr = [1, 20, 6, 4, 5]
n = len(arr)
print("Number of inversions are",
getInvCount(arr, n))
# This code is contributed by Smitha Dinesh Semwal
C#
Output:
373
Chapter 63. Count Inversions in an array Set 1 (Using Merge Sort)
374
Chapter 63. Count Inversions in an array Set 1 (Using Merge Sort)
Implementation:
C
#include <bits/stdc++.h>
int _mergeSort(int arr[], int temp[], int left, int right);
int merge(int arr[], int temp[], int left, int mid, int right);
/* This function sorts the input array and returns the
number of inversions in the array */
int mergeSort(int arr[], int array_size)
{
int *temp = (int *)malloc(sizeof(int)*array_size);
return _mergeSort(arr, temp, 0, array_size - 1);
}
/* An auxiliary recursive function that sorts the input array and
returns the number of inversions in the array. */
int _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, inv_count = 0;
if (right > left)
375
Chapter 63. Count Inversions in an array Set 1 (Using Merge Sort)
{
/* Divide the array into two parts and call _mergeSortAndCountInv()
for each of the parts */
mid = (right + left)/2;
/* Inversion count will be sum of inversions in left-part, right-part
and number of inversions in merging */
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid+1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid+1, right);
}
return inv_count;
}
/* This funt merges two sorted arrays and returns inversion count in
the arrays.*/
int merge(int arr[], int temp[], int left, int mid, int right)
{
int i, j, k;
int inv_count = 0;
i = left; /* i is index for left subarray*/
j = mid; /* j is index for right subarray*/
k = left; /* k is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right))
{
if (arr[i] <= arr[j])
{
temp[k++] = arr[i++];
}
else
{
temp[k++] = arr[j++];
/*this is tricky -- see above explanation/diagram for merge()*/
inv_count = inv_count + (mid - i);
}
}
/* Copy the remaining elements of left subarray
(if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right subarray
(if there are any) to temp*/
376
Chapter 63. Count Inversions in an array Set 1 (Using Merge Sort)
Java
377
Chapter 63. Count Inversions in an array Set 1 (Using Merge Sort)
378
Chapter 63. Count Inversions in an array Set 1 (Using Merge Sort)
return inv_count;
}
// Driver method to test the above function
public static void main(String[] args)
{
int arr[] = new int[]{1, 20, 6, 4, 5};
System.out.println("Number of inversions are " + mergeSort(arr, 5));
}
}
Output:
Note that above code modifies (or sorts) the input array. If we want to count only
inversions then we need to create a copy of original array and call mergeSort() on copy.
References:
http://www.cs.umd.edu/class/fall2009/cmsc451/lectures/Lec08-inversions.pdf
http://www.cp.eng.chula.ac.th/~piak/teaching/algo/algo2008/count-inv.htm
Improved By : Sam007
Source
https://www.geeksforgeeks.org/counting-inversions/
379
Chapter 64
Method 1 (Simple)
A simple solution is to consider all pairs one by one and check difference between every pair.
Following program implements the simple solution. We run two loops: the outer loop picks
the first element of pair, the inner loop looks for the other element. This solution doesn’t
work if there are duplicates in array as the requirement is to count only distinct pairs.
C++
380
Chapter 64. Count all distinct pairs with difference equal to k
{
int count = 0;
// Pick all elements one by one
for (int i = 0; i < n; i++)
{
// See if there is a pair of this picked element
for (int j = i+1; j < n; j++)
if (arr[i] - arr[j] == k || arr[j] - arr[i] == k )
count++;
}
return count;
}
// Driver program to test above function
int main()
{
int arr[] = {1, 5, 3, 4, 2};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
cout << "Count of pairs with given diff is "
<< countPairsWithDiffK(arr, n, k);
return 0;
}
Java
381
Chapter 64. Count all distinct pairs with difference equal to k
}
return count;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 5, 3, 4, 2 };
int n = arr.length;
int k = 3;
System.out.println("Count of pairs with given diff is "
+ countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed
// by Sahil_Bansall
Python3
C#
382
Chapter 64. Count all distinct pairs with difference equal to k
// difference k
using System;
class GFG {
static int countPairsWithDiffK(int []arr,
int n, int k)
{
int count = 0;
// Pick all elements one by one
for (int i = 0; i < n; i++)
{
// See if there is a pair
// of this picked element
for (int j = i + 1; j < n; j++)
if (arr[i] - arr[j] == k ||
arr[j] - arr[i] == k)
count++;
}
return count;
}
// Driver code
public static void Main()
{
int []arr = { 1, 5, 3, 4, 2 };
int n = arr.Length;
int k = 3;
Console.WriteLine("Count of pairs with "
+ " given diff is "
+ countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed by Sam007.
PHP
<?php
// A simple PHP program to count
// pairs with difference k
function countPairsWithDiffK($arr, $n,
$k)
383
Chapter 64. Count all distinct pairs with difference equal to k
{
$count = 0;
// Pick all elements one by one
for($i = 0; $i < $n; $i++)
{
// See if there is a pair of
// this picked element
for($j = $i + 1; $j < $n; $j++)
if ($arr[$i] - $arr[$j] == $k or
$arr[$j] - $arr[$i] == $k)
$count++;
}
return $count;
}
// Driver Code
$arr = array(1, 5, 3, 4, 2);
$n = count($arr);
$k = 3;
echo "Count of pairs with given diff is "
, countPairsWithDiffK($arr, $n, $k);
// This code is contributed by anuj_67.
?>
Output :
1) Initialize count as 0
2) Sort all numbers in increasing order.
3) Remove duplicates from array.
4) Do following for each element arr[i]
a) Binary Search for arr[i] + k in subarray from i+1 to n-1.
b) If arr[i] + k found, increment count.
5) Return count.
384
Chapter 64. Count all distinct pairs with difference equal to k
C++
385
Chapter 64. Count all distinct pairs with difference equal to k
Java
386
Chapter 64. Count all distinct pairs with difference equal to k
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 5, 3, 4, 2 };
int n = arr.length;
int k = 3;
System.out.println("Count of pairs with given diff is "
+ countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed by Sahil_Bansall
Python
387
Chapter 64. Count all distinct pairs with difference equal to k
C#
388
Chapter 64. Count all distinct pairs with difference equal to k
int n, int k)
{
int count = 0, i;
// Sort array elements
Array.Sort(arr);
// code to remove duplicates from arr[]
// Pick a first element point
for (i = 0; i < n - 1; i++)
if (binarySearch(arr, i + 1, n - 1,
arr[i] + k) != -1)
count++;
return count;
}
// Driver code
public static void Main()
{
int []arr = { 1, 5, 3, 4, 2 };
int n = arr.Length;
int k = 3;
Console.WriteLine("Count of pairs with"
+ " given diff is "
+ countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed by Sam007.
PHP
<?php
// A sorting based PHP program to
// count pairs with difference k
// Standard binary search function
function binarySearch($arr, $low,
$high, $x)
{
if ($high >= $low)
{
$mid = $low + ($high - $low)/2;
if ($x == $arr[$mid])
389
Chapter 64. Count all distinct pairs with difference equal to k
return $mid;
if ($x > $arr[$mid])
return binarySearch($arr, ($mid + 1),
$high, $x);
else
return binarySearch($arr, $low,
($mid -1), $x);
}
return -1;
}
/* Returns count of pairs with
difference k in arr[] of size n. */
function countPairsWithDiffK($arr, $n, $k)
{
$count = 0;
$i;
// Sort array elements
sort($arr);
// Code to remove duplicates
// from arr[]
// Pick a first element point
for ($i = 0; $i < $n - 1; $i++)
if (binarySearch($arr, $i + 1, $n - 1,
$arr[$i] + $k) != -1)
$count++;
return $count;
}
// Driver Code
$arr = array(1, 5, 3, 4, 2);
$n = count($arr);
$k = 3;
echo "Count of pairs with given diff is "
, countPairsWithDiffK($arr, $n, $k);
// This code is contributed by anuj-67.
?>
Output:
390
Chapter 64. Count all distinct pairs with difference equal to k
Time complexity: The first step (sorting) takes O(nLogn) time. The second step runs binary
search n times, so the time complexity of second step is also O(nLogn). Therefore, overall
time complexity is O(nLogn). The second step can be optimized to O(n), see this.
Method 3 (Use Self-balancing BST)
We can also a self-balancing BST like AVL tree or Red Black tree to solve this problem.
Following is detailed algorithm.
1) Initialize count as 0.
2) Insert all elements of arr[] in an AVL tree. While inserting,
ignore an element if already present in AVL tree.
3) Do following for each element arr[i].
a) Search for arr[i] + k in AVL tree, if found then increment count.
b) Search for arr[i] - k in AVL tree, if found then increment count.
c) Remove arr[i] from AVL tree.
Time complexity of above solution is also O(nLogn) as search and delete operations take
O(Logn) time for a self-balancing binary search tree.
Method 4 (Use Hashing)
We can also use hashing to achieve the average time complexity as O(n) for many cases.
1) Initialize count as 0.
2) Insert all distinct elements of arr[] in a hash map. While inserting,
ignore an element if already present in the hash map.
3) Do following for each element arr[i].
a) Look for arr[i] + k in the hash map, if found then increment count.
b) Look for arr[i] - k in the hash map, if found then increment count.
c) Remove arr[i] from hash table.
A very simple case where hashing works in O(n) time is the case where range of values is
very small. For example, in the following implementation, range of numbers is assumed to
be 0 to 99999. A simple hashing technique to use values as index can be used.
391
Chapter 64. Count all distinct pairs with difference equal to k
• If value diff is K, increment count and move both pointers to next element
• if value diff > k, move l to next element
• if value diff < k, move r to next element
return count
C++
392
Chapter 64. Count all distinct pairs with difference equal to k
}
else if(arr[r] - arr[l] > k)
l++;
else // arr[r] - arr[l] < sum
r++;
}
return count;
}
// Driver program to test above function
int main()
{
int arr[] = {1, 5, 3, 4, 2};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
cout << "Count of pairs with given diff is "
<< countPairsWithDiffK(arr, n, k);
return 0;
}
Java
393
Chapter 64. Count all distinct pairs with difference equal to k
C#
394
Chapter 64. Count all distinct pairs with difference equal to k
l++;
else // arr[r] - arr[l] < sum
r++;
}
return count;
}
// Driver program to test above function
public static void Main()
{
int []arr = {1, 5, 3, 4, 2};
int n = arr.Length;
int k = 3;
Console.Write("Count of pairs with "
+ "given diff is " +
countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// A sorting based program to count
// pairs with difference k
// Returns count of pairs with
// difference k in arr[] of size n.
function countPairsWithDiffK( $arr, $n, $k)
{
$count = 0;
// Sort array elements
sort($arr);
$l = 0;
$r = 0;
while($r < $n)
{
if($arr[$r] - $arr[$l] == $k)
{
$count++;
$l++;
$r++;
}
else if($arr[$r] - $arr[$l] > $k)
$l++;
395
Chapter 64. Count all distinct pairs with difference equal to k
// arr[r] - arr[l] < sum
else
$r++;
}
return $count;
}
// Driver Code
$arr = array(1, 5, 3, 4, 2);
$n =count($arr);
$k = 3;
echo "Count of pairs with given diff is "
, countPairsWithDiffK($arr, $n, $k);
// This code is contributed by anuj_67,
?>
Output:
Source
https://www.geeksforgeeks.org/count-pairs-difference-equal-k/
396
Chapter 65
Input : S = geeksforgeeks, T = ge
Output : 6
T appears in S as below three subsequences.
[ge], [ ge], [g e], [g e] [g e]
and [ g e]
397
Chapter 65. Count distinct occurrences as a subsequence
Since there are overlapping subproblems in above recurrence result, we can apply dynamic
programming approach to solve above problem. We create a 2D array mat[m+1][n+1] where
m is length of string T and n is length of string S. mat[i][j] denotes the number of distinct
subsequence of substring S(1..i) and substring T(1..j) so mat[m][n] contains our solution.
C++
398
Chapter 65. Count distinct occurrences as a subsequence
Java
399
Chapter 65. Count distinct occurrences as a subsequence
// mat[i][j] stores the count of
// occurrences of T(1..i) in S(1..j).
int mat[][] = new int[m + 1][n + 1];
// Initializing first column with
// all 0s. An emptystring can't have
// another string as suhsequence
for (int i = 1; i <= m; i++)
mat[i][0] = 0;
// Initializing first row with all 1s.
// An empty string is subsequence of all.
for (int j = 0; j <= n; j++)
mat[0][j] = 1;
// Fill mat[][] in bottom up manner
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
// If last characters don't match,
// then value is same as the value
// without last character in S.
if (T.charAt(i - 1) != S.charAt(j - 1))
mat[i][j] = mat[i][j - 1];
// Else value is obtained considering two cases.
// a) All substrings without last character in S
// b) All substrings without last characters in
// both.
else
mat[i][j] = mat[i][j - 1] + mat[i - 1][j - 1];
}
}
/* uncomment this to print matrix mat
for (int i = 1; i <= m; i++, cout << endl)
for (int j = 1; j <= n; j++)
System.out.println ( mat[i][j] +" "); */
return mat[m][n];
}
// Driver code to check above method
public static void main(String[] args)
{
String T = "ge";
String S = "geeksforgeeks";
System.out.println(findSubsequenceCount(S, T));
}
400
Chapter 65. Count distinct occurrences as a subsequence
}
// This code is contributed by vt_m
C#
401
Chapter 65. Count distinct occurrences as a subsequence
Output:
Source
https://www.geeksforgeeks.org/count-distinct-occurrences-as-a-subsequence/
402
Chapter 66
Count minimum number of subsets (or subsequences) with consecutive numbers - Geeks-
forGeeks
Given an array of distinct positive numbers, the task is to calculate the number of subsets
(or subsequences) from the array such that each subset contains consecutive numbers.
Examples:
The idea is to sort the array and traverse the sorted array to count the number of such
subsets. To count the number of such subsets, we need to count the consecutive numbers
such that difference between them is not equal to one.
Following is the algorithm for the finding number of subset containing consecutive numbers:
403
Chapter 66. Count minimum number of subsets (or subsequences) with consecutive
numbers
Java
404
Chapter 66. Count minimum number of subsets (or subsequences) with consecutive
numbers
class GFG {
// Returns count of subsets with consecutive numbers
static int numofsubset(int arr[], int n)
{
// Sort the array so that elements
// which are consecutive in nature
// became consecutive in the array.
Arrays.sort(arr);
// Initialize result
int count = 1;
for (int i = 0; i < n - 1; i++) {
// Check if there is beginning
// of another subset of
// consecutive number
if (arr[i] + 1 != arr[i + 1])
count++;
}
return count;
}
// Driven Program
public static void main(String[] args)
{
int arr[] = { 100, 56, 5, 6, 102, 58, 101,
57, 7, 103, 59 };
int n = arr.length;
System.out.println(numofsubset(arr, n));
}
}
// This code is contributed by prerna saini.
Python
405
Chapter 66. Count minimum number of subsets (or subsequences) with consecutive
numbers
# Check if there is beginning of another subset of
# consecutive number
if (x[i] + 1 != x[i + 1]):
count = count + 1
return count
# Driven Program
arr = [ 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 ]
n = len(arr)
print numofsubset(arr, n)
# This code is contributed by Afzal Ansari.
C#
406
Chapter 66. Count minimum number of subsets (or subsequences) with consecutive
numbers
{
int[] arr = { 100, 56, 5, 6, 102, 58, 101,
57, 7, 103, 59 };
int n = arr.Length;
Console.WriteLine(numofsubset(arr, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find number
// of subset containing
// consecutive numbers
// Returns count of subsets
// with consecutive numbers
function numofsubset( $arr, $n)
{
// Sort the array so that
// elements which are
// consecutive in nature
// became consecutive
// in the array.
sort($arr);
// Initialize result
$count = 1;
for ($i = 0; $i < $n - 1; $i++)
{
// Check if there is
// beginning of another
// subset of consecutive
// number
if ($arr[$i] + 1 != $arr[$i + 1])
$count++;
}
return $count;
}
// Driver Code
$arr = array(100, 56, 5, 6, 102, 58, 101,
57, 7, 103, 59 );
407
Chapter 66. Count minimum number of subsets (or subsequences) with consecutive
numbers
$n = sizeof($arr);
echo numofsubset($arr, $n);
// This code is contributed by Anuj_67
?>
Output:
Source
https://www.geeksforgeeks.org/count-minimum-number-subsets-subsequences-consecutive-numbers/
408
Chapter 67
Count number of triplets in an array having sum in the range [a, b] - GeeksforGeeks
Given an array of distinct integers and a range [a, b], the task is to count the number of
triplets having a sum in the range [a, b].
Examples:
A naive approach is to run three loops to consider all the triplets one by one. Find the sum
of each triplet and increment the count if the sum lies in a given range [a, b].
Below is the implementation of above approach:
C++
409
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
using namespace std;
// Function to count triplets
int countTriplets(int arr[], int n, int a, int b)
{
// Initialize result
int ans = 0;
// Fix the first element as A[i]
for (int i = 0; i < n - 2; i++) {
// Fix the second element as A[j]
for (int j = i + 1; j < n - 1; j++) {
// Now look for the third number
for (int k = j + 1; k < n; k++)
if (arr[i] + arr[j] + arr[k] >= a
&& arr[i] + arr[j] + arr[k] <= b)
ans++;
}
}
return ans;
}
// Driver Code
int main()
{
int arr[] = { 2, 7, 5, 3, 8, 4, 1, 9 };
int n = sizeof arr / sizeof arr[0];
int a = 8, b = 16;
cout << countTriplets(arr, n, a, b) << endl;
return 0;
}
Java
410
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
Python3
411
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
C#
412
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
PHP
413
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
<?php
// PHP program to count triplets with
// sum that lies in given range [a, b].
// Function to count triplets
function countTriplets($arr, $n, $a, $b)
{
// Initialize result
$ans = 0;
// Fix the first element as A[i]
for ($i = 0; $i < $n - 2; $i++)
{
// Fix the second element as A[j]
for ($j = $i + 1; $j < $n - 1; $j++)
{
// Now look for the third number
for ($k = $j + 1; $k < $n; $k++)
if ($arr[$i] + $arr[$j] + $arr[$k] >= $a &&
$arr[$i] + $arr[$j] + $arr[$k] <= $b)
$ans++;
}
}
return $ans;
}
// Driver Code
$arr = array( 2, 7, 5, 3, 8, 4, 1, 9 );
$n = sizeof($arr);
$a = 8; $b = 16;
echo countTriplets($arr, $n, $a, $b) . "\n";
// This code is contributed
// by Akanksha Rai(Abby_akku)
?>
Output:
36
414
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
a sum less than the lower limit a. Subtract the count of triplets having a sum less than a.
The final result is the count of triplets having a sum in the range [a, b].
The algorithm is as follows:
• Find count of triplets having a sum less than or equal to b. Let this count
be x.
• Find count of triplets having a sum less than a. Let this count be y.
• Final result is x-y.
To find the count of triplets having a sum less than or equal to given value, refer Count
triplets with sum smaller than a given value
415
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
416
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
Java
417
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
418
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
}
// This code is contributed
// by Harshit Saini
Python3
419
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
C#
420
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
421
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
}
return ans;
}
// Function to return count
// of triplets having sum
// in range [a, b].
public static int countTriplets(int[] arr, int n,
int a, int b)
{
// to store count
// of triplets.
int res;
// Find count of triplets
// having sum less than or
// equal to b and subtract
// count of triplets having
// sum less than or equal
// to a-1.
res = countTripletsLessThan(arr, n, b) -
countTripletsLessThan(arr, n, a - 1);
return res;
}
// Driver Code
public static void Main()
{
int[] arr = {2, 7, 5, 3,
8, 4, 1, 9};
int n = arr.Length;
int a = 8, b = 16;
Console.WriteLine("" + countTriplets(arr, n,
a, b));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
Output:
36
422
Chapter 67. Count number of triplets in an array having sum in the range [a, b]
Source
https://www.geeksforgeeks.org/count-number-of-triplets-in-an-array-having-sum-in-the-range-a-b/
423
Chapter 68
Count number of triplets with product equal to given number Set 2 - GeeksforGeeks
Given an array of distinct integers(considering only positive numbers) and a number ‘m’,
find the number of triplets with the product equal to ‘m’.
Examples:
Input: arr[] = { 1, 4, 6, 2, 3, 8}
m = 24
Output: 3
Input: arr[] = { 0, 4, 6, 2, 3, 8}
m = 18
Output: 0
An approach with O(n) extra space has already been discussed in previous post. In this
post an approach with O(1) space complexity will be discussed.
Approach: The idea is to use Three-pointer technique:
424
Chapter 68. Count number of triplets with product equal to given number Set 2
Source
https://www.geeksforgeeks.org/count-number-of-triplets-with-product-equal-to-given-number-set-2-2/
C++
425
Chapter 68. Count number of triplets with product equal to given number Set 2
return count;
}
// Drivers code
int main()
{
int arr[] = { 1, 1, 1, 1, 1, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
int m = 1;
cout << countTriplets(arr, n, m);
return 0;
}
Java
426
Chapter 68. Count number of triplets with product equal to given number Set 2
C#
// C# implementation of above approach
using System;
class GFG
427
Chapter 68. Count number of triplets with product equal to given number Set 2
{
// Function to count such triplets
static int countTriplets(int []arr,
int n, int m)
{
int count = 0;
// Sort the array
Array.Sort(arr);
int end, start, mid;
// three pointer technique
for (end = n – 1; end >= 2; end–)
{
start = 0; mid = end – 1;
while (start < mid) { // Calculate the product // of a triplet long prod = arr[end] * arr[start]
* arr[mid]; // Check if that product // is greater than m, // decrement mid if (prod > m)
mid–;
// Check if that product
// is greater than m,
// increment start
else if (prod < m) start++; // Check if that product // is greater than m, // decrement mid,
increment // start and increment the // count of pairs else if (prod == m) { count++; mid-
-; start++; } } } return count; } // Driver code public static void Main (String []args) { int
[]arr = { 1, 1, 1, 1, 1, 1 }; int n = arr.Length; int m = 1; Console.WriteLine(countTriplets(arr,
n, m)); } } // This code is contributed // by Arnab Kundu [tabbyending]
Output:
428
Chapter 69
429
Chapter 69. Count of index pairs with equal elements in an array
// Return the number of pairs with equal
// values.
int countPairs(int arr[], int n)
{
int ans = 0;
// for each index i and j
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
// finding the index with same
// value but different index.
if (arr[i] == arr[j])
ans++;
return ans;
}
// Driven Program
int main()
{
int arr[] = { 1, 1, 2 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << countPairs(arr, n) << endl;
return 0;
}
Java
430
Chapter 69. Count of index pairs with equal elements in an array
}
//driver code
public static void main (String[] args)
{
int arr[] = { 1, 1, 2 };
int n = arr.length;
System.out.println(countPairs(arr, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program to
# count of pairs with equal
# elements in an array.
# Return the number of
# pairs with equal values.
def countPairs(arr, n):
ans = 0
# for each index i and j
for i in range(0 , n):
for j in range(i + 1, n):
# finding the index
# with same value but
# different index.
if (arr[i] == arr[j]):
ans += 1
return ans
# Driven Code
arr = [1, 1, 2 ]
n = len(arr)
print(countPairs(arr, n))
# This code is contributed
# by Smitha
C#
431
Chapter 69. Count of index pairs with equal elements in an array
// elements in an array.
using System;
class GFG {
// Return the number of pairs with equal
// values.
static int countPairs(int []arr, int n)
{
int ans = 0;
// for each index i and j
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
// finding the index with same
// value but different index.
if (arr[i] == arr[j])
ans++;
return ans;
}
// Driver code
public static void Main ()
{
int []arr = { 1, 1, 2 };
int n = arr.Length;
Console.WriteLine(countPairs(arr, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to count of
// pairs with equal elements
// in an array.
// Return the number of pairs
// with equal values.
function countPairs( $arr, $n)
{
$ans = 0;
// for each index i and j
432
Chapter 69. Count of index pairs with equal elements in an array
Output :
433
Chapter 69. Count of index pairs with equal elements in an array
// Calculating pairs of each value.
int ans = 0;
for (auto it=mp.begin(); it!=mp.end(); it++)
{
int count = it->second;
ans += (count * (count - 1))/2;
}
return ans;
}
// Driven Program
int main()
{
int arr[] = {1, 1, 2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << countPairs(arr, n) << endl;
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/count-index-pairs-equal-elements-array/
434
Chapter 70
Count pairs from two linked lists whose sum is equal to a given value - GeeksforGeeks
Given two linked lists(can be sorted or unsorted) of size n1 and n2 of distinct elements.
Given a value x. The problem is to count all pairs from both lists whose sum is equal to
the given value x.
Note: The pair has an element from each linked list.
Examples:
Method 1 (Naive Approach): Using two loops pick elements from both the linked lists
and check whether the sum of the pair is equal to x or not.
C/C++
435
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
436
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
Java
437
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
Output:
Count = 2
438
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
Method 2 (Sorting): Sort the 1st linked list in ascending order and the 2nd linked list in
descending order using merge sort technique. Now traverse both the lists from left to right
in the following way:
Algorithm:
countPairs(list1, list2, x)
Initialize count = 0
while list != NULL and list2 != NULL
if (list1->data + list2->data) == x
list1 = list1->next
list2 = list2->next
count++
else if (list1->data + list2->data) > x
list2 = list2->next
else
list1 = list1->next
return count
For simplicity, the implementation given below assumes that list1 is sorted in ascending
order and list2 is sorted in descending order.
C/C++
439
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
440
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
return count;
}
// Driver program to test above
int main()
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
// create linked list1 1->3->5->7
// assumed to be in ascending order
push(&head1, 7);
push(&head1, 5);
push(&head1, 3);
push(&head1, 1);
// create linked list2 8->5->3->2
// assumed to be in descending order
push(&head2, 2);
push(&head2, 3);
push(&head2, 5);
push(&head2, 8);
int x = 10;
cout << "Count = "
<< countPairs(head1, head2, x);
return 0;
}
Java
441
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
{
int count = 0;
// sort head1 in ascending order and
// head2 in descending order
Collections.sort(head1);
Collections.sort(head2,Collections.reverseOrder());
// traverse both the lists from left to right
Iterator<Integer> itr1 = head1.iterator();
Iterator<Integer> itr2 = head2.iterator();
Integer num1 = itr1.hasNext() ? itr1.next() : null;
Integer num2 = itr2.hasNext() ? itr2.next() : null;
while(num1 != null && num2 != null)
{
// if this sum is equal to 'x', then move both
// the lists to next nodes and increment 'count'
if ((num1 + num2) == x)
{
num1 = itr1.hasNext() ? itr1.next() : null;
num2 = itr2.hasNext() ? itr2.next() : null;
count++;
}
// if this sum is greater than x, then
// move itr2 to next node
else if ((num1 + num2) > x)
num2 = itr2.hasNext() ? itr2.next() : null;
// else move itr1 to next node
else
num1 = itr1.hasNext() ? itr1.next() : null;
}
// required count of pairs
return count;
}
// Driver method
public static void main(String[] args)
{
Integer arr1[] = {3, 1, 5, 7};
442
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
Output:
Count = 2
443
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
444
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
// create linked list1 3->1->5->7
push(&head1, 7);
push(&head1, 5);
push(&head1, 1);
push(&head1, 3);
// create linked list2 8->2->5->3
push(&head2, 3);
push(&head2, 5);
push(&head2, 2);
push(&head2, 8);
int x = 10;
cout << "Count = "
<< countPairs(head1, head2, x);
return 0;
}
Java
445
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
Output:
Count = 2
446
Chapter 70. Count pairs from two linked lists whose sum is equal to a given value
Source
https://www.geeksforgeeks.org/count-pairs-two-linked-lists-whose-sum-equal-given-value/
447
Chapter 71
Count pairs from two sorted arrays whose sum is equal to a given value x - GeeksforGeeks
Given two sorted arrays of size m and n of distinct elements. Given a value x. The problem
is to count all pairs from both arrays whose sum is equal to x.
Note: The pair has an element from each array.
Examples :
Output : 2
The pairs are:
(5, 5) and (7, 3)
Output : 5
Method 1 (Naive Approach): Using two loops pick elements from both the arrays and
check whether the sum of the pair is equal to x or not.
C++
448
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
Java
449
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
import java.io.*;
class GFG {
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
static int countPairs(int []arr1,
int []arr2, int m, int n, int x)
{
int count = 0;
// generating pairs from
// both the arrays
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
// if sum of pair is equal
// to 'x' increment count
if ((arr1[i] + arr2[j]) == x)
count++;
// required count of pairs
return count;
}
// Driver Code
public static void main (String[] args)
{
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 3, 5, 8};
int m = arr1.length;
int n = arr2.length;
int x = 10;
System.out.println( "Count = "
+ countPairs(arr1, arr2, m, n, x));
}
}
// This code is contributed by anuj_67.
Python3
450
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
C#
451
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
{
int count = 0;
// generating pairs from
// both the arrays
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
// if sum of pair is equal
// to 'x' increment count
if ((arr1[i] + arr2[j]) == x)
count++;
// required count of pairs
return count;
}
// Driver Code
public static void Main ()
{
int []arr1 = {1, 3, 5, 7};
int []arr2 = {2, 3, 5, 8};
int m = arr1.Length;
int n = arr2.Length;
int x = 10;
Console.WriteLine( "Count = "
+ countPairs(arr1, arr2, m, n, x));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP implementation to count
// pairs from both sorted arrays
// whose sum is equal to a given
// value
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
function countPairs( $arr1, $arr2,
452
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
Output :
Count = 2
453
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
454
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
// required count of pairs
return count;
}
// Driver Code
int main()
{
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 3, 5, 8};
int m = sizeof(arr1) / sizeof(arr1[0]);
int n = sizeof(arr2) / sizeof(arr2[0]);
int x = 10;
cout << "Count = "
<< countPairs(arr1, arr2, m, n, x);
return 0;
}
Java
455
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
C#
456
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
using System;
class GFG {
// function to search 'value' in the given
// array 'arr[]' it uses binary search
// technique as 'arr[]' is sorted
static bool isPresent(int []arr, int low,
int high, int value)
{
while (low <= high)
{
int mid = (low + high) / 2;
// value found
if (arr[mid] == value)
return true;
else if (arr[mid] > value)
high = mid - 1;
else
low = mid + 1;
}
// value not found
return false;
}
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
static int countPairs(int []arr1, int []arr2,
int m, int n, int x)
{
int count = 0;
for (int i = 0; i < m; i++)
{
// for each arr1[i]
int value = x - arr1[i];
// check if the 'value'
// is present in 'arr2[]'
if (isPresent(arr2, 0, n - 1, value))
count++;
}
457
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
// required count of pairs
return count;
}
// Driver Code
public static void Main ()
{
int []arr1 = {1, 3, 5, 7};
int []arr2 = {2, 3, 5, 8};
int m = arr1.Length;
int n = arr2.Length;
int x = 10;
Console.WriteLine("Count = "
+ countPairs(arr1, arr2, m, n, x));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP implementation to count
// pairs from both sorted arrays
// whose sum is equal to a given
// value
// function to search 'value'
// in the given array 'arr[]'
// it uses binary search technique
// as 'arr[]' is sorted
function isPresent($arr, $low,
$high, $value)
{
while ($low <= $high)
{
$mid = ($low + $high) / 2;
// value found
if ($arr[$mid] == $value)
return true;
else if ($arr[$mid] > $value)
$high = $mid - 1;
else
$low = $mid + 1;
}
458
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
// value not found
return false;
}
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
function countPairs($arr1, $arr2,
$m, $n, $x)
{
$count = 0;
for ($i = 0; $i < $m; $i++)
{
// for each arr1[i]
$value = $x - $arr1[$i];
// check if the 'value'
// is present in 'arr2[]'
if (isPresent($arr2, 0,
$n - 1, $value))
$count++;
}
// required count of pairs
return $count;
}
// Driver Code
$arr1 = array(1, 3, 5, 7);
$arr2 = array(2, 3, 5, 8);
$m = count($arr1);
$n = count($arr2);
$x = 10;
echo "Count = "
, countPairs($arr1, $arr2, $m, $n, $x);
// This code is contributed by anuj_67.
?>
Output :
Count = 2
Time Complexity : O(mlogn), searching should be applied on the array which is of greater
459
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
460
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
Output :
Count = 2
countPairs(arr1, arr2, m, n, x)
Initialize l = 0, r = n - 1
Initialize count = 0
loop while l = 0
if (arr1[l] + arr2[r]) == x
l++, r--
count++
else if (arr1[l] + arr2[r]) < x
l++
else
r--
return count
C++
461
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
#include <bits/stdc++.h>
using namespace std;
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
int countPairs(int arr1[], int arr2[],
int m, int n, int x)
{
int count = 0;
int l = 0, r = n - 1;
// traverse 'arr1[]' from
// left to right
// traverse 'arr2[]' from
// right to left
while (l < m && r >= 0)
{
// if this sum is equal
// to 'x', then increment 'l',
// decrement 'r' and
// increment 'count'
if ((arr1[l] + arr2[r]) == x)
{
l++; r--;
count++;
}
// if this sum is less
// than x, then increment l
else if ((arr1[l] + arr2[r]) < x)
l++;
// else decrement 'r'
else
r--;
}
// required count of pairs
return count;
}
// Driver Code
int main()
{
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 3, 5, 8};
462
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
Java
463
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
l++;
// else decrement 'r'
else
r--;
}
// required count of pairs
return count;
}
// Driver Code
public static void main (String[] args)
{
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 3, 5, 8};
int m = arr1.length;
int n = arr2.length;
int x = 10;
System.out.println( "Count = "
+ countPairs(arr1, arr2, m, n, x));
}
}
// This code is contributed by anuj_67.
C#
// C# implementation to count
// pairs from both sorted arrays
// whose sum is equal to a given
// value
using System;
class GFG {
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
static int countPairs(int []arr1,
int []arr2, int m, int n, int x)
{
int count = 0;
int l = 0, r = n - 1;
// traverse 'arr1[]' from
// left to right
464
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
PHP
<?php
// PHP implementation to count
465
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
466
Chapter 71. Count pairs from two sorted arrays whose sum is equal to a given value x
$m = count($arr1);
$n = count($arr2);
$x = 10;
echo "Count = "
, countPairs($arr1, $arr2, $m, $n, $x);
// This code is contributed by anuj_67
?>
Output :
Count = 2
Source
https://www.geeksforgeeks.org/count-pairs-two-sorted-arrays-whose-sum-equal-given-value-x/
467
Chapter 72
Count pairs from two sorted matrices with given sum - GeeksforGeeks
Given two sorted matrices mat1 and mat2 of size n x n of distinct elements. Given a value
x. The problem is to count all pairs from both matrices whose sum is equal to x.
Note: The pair has an element from each matrix. Matrices are strictly sorted which means
that matrices are sorted in a way such that all elements in a row are sorted in increasing
order and for row ‘i’, where 1 <= i <= n-1, first element of row ’i’ is greater than the last
element of row ’i-1’.
Examples:
Method 1 (Naive Approach): For each element ele of mat1[][] linearly search (x – ele)
in mat2[][].
C++
468
Chapter 72. Count pairs from two sorted matrices with given sum
469
Chapter 72. Count pairs from two sorted matrices with given sum
int mat2[][SIZE] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
cout << "Count = "
<< countPairs(mat1, mat2, n, x);
return 0;
}
Java
470
Chapter 72. Count pairs from two sorted matrices with given sum
int count = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
// if value (x-mat1[i][j]) is
// found in mat2[][]
if (valuePresent(mat2, n, x - mat1[i][j]))
count++;
}
// required count of pairs
return count;
}
// Driver program
public static void main (String[] args)
{
int mat1[][] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
System.out.println ("Count = " +
countPairs(mat1, mat2, n, x));
}
}
// This article is contributed by vt_m
Python3
471
Chapter 72. Count pairs from two sorted matrices with given sum
C#
472
Chapter 72. Count pairs from two sorted matrices with given sum
473
Chapter 72. Count pairs from two sorted matrices with given sum
int [,]mat1 = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int [,]mat2 = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
Console.WriteLine("Count = " +
countPairs(mat1, mat2, n, x));
}
}
// This article is contributed by vt_m
Output:
Count = 4
474
Chapter 72. Count pairs from two sorted matrices with given sum
475
Chapter 72. Count pairs from two sorted matrices with given sum
// else false
bool searchValue(int mat[][SIZE],
int n, int val)
{
// to get the row index number of the largest element
// smaller than equal to 'val' in mat[][]
int row_no = binarySearchOnRow(mat, 0, n - 1, val);
// if no such row exists, then
// 'val' is not present
if (row_no == -1)
return false;
// to search 'val' in mat[row_no][]
return binarySearchOnCol(mat, 0, n - 1, val, row_no);
}
// function to count pairs from two sorted matrices
// whose sum is equal to a given value x
int countPairs(int mat1[][SIZE], int mat2[][SIZE],
int n, int x)
{
int count = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// if value (x-mat1[i][j]) is found in mat2[][]
if (searchValue(mat2, n, x - mat1[i][j]))
count++;
// required count of pairs
return count;
}
// Driver program to test above
int main()
{
int mat1[][SIZE] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][SIZE] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
476
Chapter 72. Count pairs from two sorted matrices with given sum
Java
477
Chapter 72. Count pairs from two sorted matrices with given sum
{
int mid = (l + h) / 2;
// 'val' found
if (mat[row][mid] == val)
return true;
// search in mat[row][mid+1...h]
else if (mat[row][mid] < val)
l = mid + 1;
// search in mat[row][l...mid-1]
else
h = mid - 1;
}
// 'val' not found
return false;
}
// function to search 'val' in mat[][]
// returns true if 'val' is present
// else false
static boolean searchValue(int mat[][],
int n, int val)
{
// to get the row index number
// of the largest element smaller
// than equal to 'val' in mat[][]
int row_no = binarySearchOnRow(mat, 0, n - 1, val);
// if no such row exists, then
// 'val' is not present
if (row_no == -1)
return false;
// to search 'val' in mat[row_no][]
return binarySearchOnCol(mat, 0, n - 1, val, row_no);
}
// function to count pairs from
// two sorted matrices whose sum
// is equal to a given value x
static int countPairs(int mat1[][], int mat2[][],
int n, int x)
{
int count = 0;
478
Chapter 72. Count pairs from two sorted matrices with given sum
C#
// C# implementation to count
// pairs from two sorted matrices
// whose sum is equal to a given
// value x
using System;
class GFG
{
//int SIZE= 10;
// function returns the row index no of largest
// element smaller than equal to 'x' in first
// column of mat[][]. If no such element exists
479
Chapter 72. Count pairs from two sorted matrices with given sum
480
Chapter 72. Count pairs from two sorted matrices with given sum
481
Chapter 72. Count pairs from two sorted matrices with given sum
Output:
Count = 4
482
Chapter 72. Count pairs from two sorted matrices with given sum
Output:
Count = 4
483
Chapter 72. Count pairs from two sorted matrices with given sum
484
Chapter 72. Count pairs from two sorted matrices with given sum
if (c1 == n) {
// reset 'c1'
c1 = 0;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left boundary
if (c2 == -1) {
// reset 'c2'
c2 = n - 1;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return count;
}
// Driver program to test above
int main()
{
int mat1[][SIZE] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][SIZE] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
cout << "Count = "
<< countPairs(mat1, mat2, n, x);
return 0;
}
Java
485
Chapter 72. Count pairs from two sorted matrices with given sum
486
Chapter 72. Count pairs from two sorted matrices with given sum
c2--;
// if 'c1' crosses right boundary
if (c1 == n) {
// reset 'c1'
c1 = 0;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left boundary
if (c2 == -1) {
// reset 'c2'
c2 = n - 1;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return count;
}
// Driver code
public static void main (String[] args)
{
int mat1[][] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
System.out.println ( "Count = " +
countPairs(mat1, mat2, n, x));
}
}
// This article is contributed by vt_m
487
Chapter 72. Count pairs from two sorted matrices with given sum
C#
488
Chapter 72. Count pairs from two sorted matrices with given sum
c1++;
// else move mat2[][] column
// 'c2' to left
else
c2--;
// if 'c1' crosses right
// boundary
if (c1 == n) {
// reset 'c1'
c1 = 0;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left
// boundary
if (c2 == -1) {
// reset 'c2'
c2 = n - 1;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return count;
}
// Driver code
public static void Main ()
{
int [,]mat1 = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int [,]mat2 = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
489
Chapter 72. Count pairs from two sorted matrices with given sum
Output:
Count = 4
Source
https://www.geeksforgeeks.org/count-pairs-two-sorted-matrices-given-sum/
490
Chapter 73
A Simple solution is to run two loops. Pick each element of array one-by-one and for each
element find element on right side of array that hold condition, then increment counter and
last return counter value.
Below is the implementation of above idea:
C++
491
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
Java
492
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
Python3
C#
493
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
class GFG
{
// Return count of pair in given array
// such that i*arr[i] > j*arr[j]
public static int CountPair(int []arr , int n )
{
// Initialize result
int result = 0;
for (int i = 0; i < n; i++)
{
// Generate all pair and increment
// counter if the hold given condition
for (int j = i + 1; j < n; j++)
if (i*arr[i] > j*arr[j] )
result ++;
}
return result;
}
/* Driver program to test above function */
public static void Main()
{
int []arr = {5, 0, 10, 2, 4, 1, 6};
int n = arr.Length;
Console.WriteLine("Count of Pairs : " +
CountPair(arr, n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to count all pair that
// hold condition i*arr[i] > j*arr[j]
// Return count of pair in given array
// such that i*arr[i] > j*arr[j]
function CountPair($arr , $n )
{
// Initialize result
$result = 0;
494
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
Output:
Count of Pairs : 5
495
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
496
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
{
/* Divide the array into two parts and call
_mergeSortAndCountInv() for each of
the parts */
mid = (right + left)/2;
/* Inversion count will be sum of inversions in
left-part, right-part and number of inversions
in merging */
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid+1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid+1, right);
}
return inv_count;
}
/* This function sorts the input array and
returns the number of inversions in the
array */
int countPairs(int arr[], int n)
{
// Modify the array so that problem reduces to
// count inversion problem.
for (int i=0; i<n; i++)
arr[i] = i*arr[i];
// Count inversions using same logic as
// below post
// https://www.geeksforgeeks.org/counting-inversions/
int temp[n];
return _mergeSort(arr, temp, 0, n - 1);
}
// Driver code
int main()
{
int arr[] = {5, 0, 10, 2, 4, 1, 6};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Count of Pairs : "
<< countPairs(arr, n);
return 0;
}
Java
497
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
498
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
return inv_count;
}
/* An auxiliary recursive function
that sorts the input array and
returns the number of inversions
in the array. */
static int _mergeSort(int arr[], int temp[],
int left,int right)
{
int mid, inv_count = 0;
if (right > left)
{
/* Divide the array into two parts and call
_mergeSortAndCountInv() for each of
the parts */
mid = (right + left) / 2;
// Inversion count will be sum of inversions in
// left-part, right-part and number of inversions
// in merging
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid+1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid+1, right);
}
return inv_count;
}
// This function sorts the input array and
// returns the number of inversions in the
// array
static int countPairs(int arr[], int n)
{
// Modify the array so that problem reduces to
// count inversion problem.
for (int i = 0; i < n; i++)
arr[i] = i * arr[i];
// Count inversions using same logic as
// below post
// https://www.geeksforgeeks.org/counting-inversions/
int temp[] = new int [n];
return _mergeSort(arr, temp, 0, n - 1);
}
499
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
C#
500
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
/* Copy the remaining elements of left
subarray (if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];
/* Copy the remaining elements of right
subarray (if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];
// Copy back the merged elements
// to original array
for (i = left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
/* An auxiliary recursive function
that sorts the input array and
returns the number of inversions
in the array. */
static int _mergeSort(int []arr, int []temp,
int left,int right)
{
int mid, inv_count = 0;
if (right > left)
{
/* Divide the array into two parts and call
_mergeSortAndCountInv() for each of
the parts */
mid = (right + left) / 2;
// Inversion count will be sum of inversions in
// left-part, right-part and number of inversions
// in merging
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid+1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid+1, right);
}
return inv_count;
}
// This function sorts the input array and
501
Chapter 73. Count pairs in an array that hold i*arr[i] > j*arr[j]
Output:
Count of Pairs : 5
Source
https://www.geeksforgeeks.org/count-pairs-array-hold-iarri-jarrj/
502
Chapter 74
Calculate how many people will get stuck at any point due to the barriers. Use of extra
space to keep track of different points on x axis is not allowed.
503
Chapter 74. Count points covered by given intervals
Examples:
504
Chapter 74. Count points covered by given intervals
505
Chapter 74. Count points covered by given intervals
Output :
14
We can easily note that there is no importance of y in the question, so it may not be stored.
Time Complexity : O(n Log n)
Source
https://www.geeksforgeeks.org/count-points-covered-by-given-intervals/
506
Chapter 75
Count quadruples from four sorted arrays whose sum is equal to a given value x - Geeks-
forGeeks
Given four sorted arrays each of size n of distinct elements. Given a value x. The problem
is to count all quadruples(group of four numbers) from all the four arrays whose sum is
equal to x.
Note: The quadruple has an element from each of the four arrays.
Examples:
Output : 4
The quadruples are:
(4, 8, 10, 8), (5, 7, 10, 8),
(5, 8, 10, 7), (6, 7, 10, 7)
Method 1 (Naive Approach): Using four nested loops generate all quadruples and check
whether elements in the quadruple sum up to x or not.
507
Chapter 75. Count quadruples from four sorted arrays whose sum is equal to a given value
x
C++
// C++ implementation to count quadruples from four sorted arrays
// whose sum is equal to a given value x
#include <bits/stdc++.h>
using namespace std;
// function to count all quadruples from
// four sorted arrays whose sum is equal
// to a given value x
int countQuadruples(int arr1[], int arr2[],
int arr3[], int arr4[], int n, int x)
{
int count = 0;
// generate all possible quadruples from
// the four sorted arrays
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
for (int l = 0; l < n; l++)
// check whether elements of
// quadruple sum up to x or not
if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x)
count++;
// required count of quadruples
return count;
}
// Driver program to test above
int main()
{
// four sorted arrays each of size 'n'
int arr1[] = { 1, 4, 5, 6 };
int arr2[] = { 2, 3, 7, 8 };
int arr3[] = { 1, 4, 6, 10 };
int arr4[] = { 2, 4, 7, 8 };
int n = sizeof(arr1) / sizeof(arr1[0]);
int x = 30;
cout << "Count = "
<< countQuadruples(arr1, arr2, arr3,
arr4, n, x);
return 0;
}
508
Chapter 75. Count quadruples from four sorted arrays whose sum is equal to a given value
x
Python3
Output:
Count = 4
509
Chapter 75. Count quadruples from four sorted arrays whose sum is equal to a given value
x
510
Chapter 75. Count quadruples from four sorted arrays whose sum is equal to a given value
x
Output:
Count = 4
511
Chapter 75. Count quadruples from four sorted arrays whose sum is equal to a given value
x
512
Chapter 75. Count quadruples from four sorted arrays whose sum is equal to a given value
x
Output:
Count = 4
513
Chapter 75. Count quadruples from four sorted arrays whose sum is equal to a given value
x
#include <bits/stdc++.h>
using namespace std;
// function to count all quadruples from four sorted
// arrays whose sum is equal to a given value x
int countQuadruples(int arr1[], int arr2[], int arr3[],
int arr4[], int n, int x)
{
int count = 0;
// unordered_map 'um' implemented as hash table
// for <sum, frequency> tuples
unordered_map<int, int> um;
// count frequency of each sum obtained from the
// pairs of arr1[] and arr2[] and store them in 'um'
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
um[arr1[i] + arr2[j]]++;
// generate pair from arr3[] and arr4[]
for (int k = 0; k < n; k++)
for (int l = 0; l < n; l++) {
// calculate the sum of elements in
// the pair so generated
int p_sum = arr3[k] + arr4[l];
// if 'x-p_sum' is present in 'um' then
// add frequency of 'x-p_sum' to 'count'
if (um.find(x - p_sum) != um.end())
count += um[x - p_sum];
}
// required count of quadruples
return count;
}
// Driver program to test above
int main()
{
// four sorted arrays each of size 'n'
int arr1[] = { 1, 4, 5, 6 };
int arr2[] = { 2, 3, 7, 8 };
int arr3[] = { 1, 4, 6, 10 };
int arr4[] = { 2, 4, 7, 8 };
514
Chapter 75. Count quadruples from four sorted arrays whose sum is equal to a given value
x
Output:
Count = 4
Source
https://www.geeksforgeeks.org/count-quadruples-four-sorted-arrays-whose-sum-equal-given-value-x/
515
Chapter 76
Counting Sort
2) Modify the count array such that each element at each index
stores the sum of previous counts.
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 2 4 4 5 6 6 7 7 7
516
Chapter 76. Counting Sort
517
Chapter 76. Counting Sort
Java
518
Chapter 76. Counting Sort
Python
519
Chapter 76. Counting Sort
ans[i] = output[i]
return ans
# Driver program to test above function
arr = "geeksforgeeks"
ans = countSort(arr)
print "Sorted character array is %s" %("".join(ans))
# This code is contributed by Nikhil Kumar Singh
C#
520
Chapter 76. Counting Sort
--count[arr[i]];
}
// Copy the output array to arr, so
// that arr now contains sorted
// characters
for (int i = 0; i<n; ++i)
arr[i] = output[i];
}
// Driver method
public static void Main()
{
char []arr = {'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's'
};
countsort(arr);
Console.Write("Sorted character array is ");
for (int i=0; i<arr.Length; ++i)
Console.Write(arr[i]);
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP Program for counting sort
$RANGE = 255;
// The main function that sort
// the given string arr[] in
// alphabatical order
function countSort($arr)
{
global $RANGE;
// The output character array
// that will have sorted arr
$output = array(strlen($arr));
$len = strlen($arr);
// Create a count array to
521
Chapter 76. Counting Sort
Output:
522
Chapter 76. Counting Sort
Time Complexity: O(n+k) where n is the number of elements in input array and k is the
range of input.
Auxiliary Space: O(n+k)
Points to be noted:
1. Counting sort is efficient if the range of input data is not significantly greater than the
number of objects to be sorted. Consider the situation where the input sequence is between
range 1 to 10K and the data is 10, 5, 10K, 5K.
2. It is not a comparison based sorting. It running time complexity is O(n) with space
proportional to the range of data.
3. It is often used as a sub-routine to another sorting algorithm like radix sort.
4. Counting sort uses a partial hashing to count the occurrence of the data object in O(1).
5. Counting sort can be extended to work for negative inputs also.
Exercise:
1. Modify above code to sort the input data in the range from M to N.
2. Modify above code to sort negative input data.
3. Is counting sort stable and online?
4. Thoughts on parallelizing the counting sort algorithm.
Snapshots:
523
Chapter 76. Counting Sort
524
Chapter 76. Counting Sort
525
Chapter 76. Counting Sort
526
Chapter 76. Counting Sort
527
Chapter 76. Counting Sort
528
Chapter 76. Counting Sort
529
Chapter 76. Counting Sort
530
Chapter 76. Counting Sort
Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort,
Counting Sort, Bucket Sort, ShellSort, Comb Sort, PegionHole Sorting
This article is compiled byAashish Barnwal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Mithun Kumar, spattk
Source
https://www.geeksforgeeks.org/counting-sort/
531
Chapter 77
Input : arr[] = { 3, 2, 1, 4, 5 }
Output : 3
before sort: 3 2 1 4 5
\ | / | |
\|/ | |
/ | \ | |
After sort : 1 2 3 4 5
line (1 to 1) cross line (2 to 2)
line (1 to 1) cross line (3 to 3)
line (2 to 2) cross line (3 to 3)
Note: the line between two 4s and the line
between two 5s don't cross any other lines;
Input : arr[] = { 5, 4, 3, 1 }
Output : 6
Simple solution of this problem is based on the insertion sort. we simply pick each array
elements one-by-one and try to find it’s proper position in the sorted array.during finding
it’s appropriate position of an element we have to cross all the element_line whose value is
greater than current element.
Below is the implementation of above idea :
C++
532
Chapter 77. Counting cross lines in an array
Java
533
Chapter 77. Counting cross lines in an array
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1],
// that are greater than key,
// to one position ahead of
// their current position
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
// increment cross
// line by one
count_crossline++;
}
arr[j + 1] = key;
}
return count_crossline;
}
// Driver Code
public static void main(String args[])
{
int arr[] = new int[]{ 4, 3, 1, 2 };
int n = arr.length;
System.out.print(countCrossLine(arr, n));
}
}
// This code is contributed by Sam007
C#
534
Chapter 77. Counting cross lines in an array
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1],
that are greater than key, to one
position ahead of their current
position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
// increment cross line by one
count_crossline++;
}
arr[j + 1] = key;
}
return count_crossline;
}
// Driver code
public static void Main()
{
int []arr = new int[]{ 4, 3, 1, 2 };
int n = arr.Length;
Console.Write(countCrossLine(arr, n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to count
// cross line in array
// Function return count
// of cross line in an array
function countCrossLine($arr, $n)
{
$count_crossline = 0;
$i; $key; $j;
for ($i = 1; $i < $n; $i++)
{
535
Chapter 77. Counting cross lines in an array
$key = $arr[$i];
$j = $i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while ($j >= 0 and $arr[$j] > $key)
{
$arr[$j + 1] = $arr[$j];
$j = $j - 1;
// increment cross line by one
$count_crossline++;
}
$arr[$j + 1] = $key;
}
return $count_crossline;
}
// Driver Code
$arr = array( 4, 3, 1, 2 );
$n = count($arr);
echo countCrossLine($arr, $n);
// This code is contributed by anuj_67.
?>
536
Chapter 77. Counting cross lines in an array
During mer
Below c++ implementation of above idea.
537
Chapter 77. Counting cross lines in an array
are any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r, int* count_crossline)
{
if (l < r) {
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
mergeSort(arr, l, m, count_crossline);
mergeSort(arr, m + 1, r, count_crossline);
merge(arr, l, m, r, count_crossline);
}
}
// function return count of cross line in an array
int countCrossLine(int arr[], int n)
{
int count_crossline = 0;
mergeSort(arr, 0, n - 1, &count_crossline);
return count_crossline;
}
// driver program to test above function
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
538
Chapter 77. Counting cross lines in an array
Output:
10
Source
https://www.geeksforgeeks.org/counting-cross-lines-array/
539
Chapter 78
Cycle Sort
540
Chapter 78. Cycle Sort
We one by one consider all cycles. We first consider the cycle that includes first element.
We find correct position of first element, place it at its correct position, say j. We consider
old value of arr[j] and find its correct position, we keep doing this till all elements of current
cycle are placed at correct position, i.e., we don’t come back to cycle starting point.
Explanation :
arr[] = {10, 5, 2, 3}
index = 0 1 2 3
cycle_start = 0
item = 10 = arr[0]
Again rotate rest cycle that start with index '0' and item = 5
we swap item with element at arr[2].
arr[] = {10, 3, 5, 10 }
541
Chapter 78. Cycle Sort
item = 2
Again rotate rest cycle that start with index '0' and item = 2
arr[] = {2, 3, 5, 10}
CPP
542
Chapter 78. Cycle Sort
Java
543
Chapter 78. Cycle Sort
544
Chapter 78. Cycle Sort
item = arr[pos];
arr[pos] = temp;
writes++;
}
}
}
}
// Driver program to test above function
public static void main(String[] args)
{
int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 };
int n = arr.length;
cycleSort(arr, n);
System.out.println("After sort : ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
// Code Contributed by Mohit Gupta_OMG <(0_o)>
Python3
545
Chapter 78. Cycle Sort
writes += 1
# Rotate the rest of the cycle.
while pos != cycleStart:
# Find where to put the item.
pos = cycleStart
for i in range(cycleStart + 1, len(array)):
if array[i] < item:
pos += 1
# Put the item there or right after any duplicates.
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
writes += 1
return writes
# driver code
arr = [1, 8, 3, 9, 10, 10, 2, 4 ]
n = len(arr)
cycleSort(arr)
print("After sort : ")
for i in range(0, n) :
print(arr[i], end = ' ')
# Code Contributed by Mohit Gupta_OMG <(0_o)>
C#
546
Chapter 78. Cycle Sort
547
Chapter 78. Cycle Sort
}
// Driver program to test above function
public static void Main()
{
int[] arr = { 1, 8, 3, 9, 10, 10, 2, 4 };
int n = arr.Length;
// Function calling
cycleSort(arr, n);
Console.Write("After sort : ");
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Nitin Mittal
Output:
After sort :
1 2 3 4 8 9 10 10
Source
https://www.geeksforgeeks.org/cycle-sort/
548
Chapter 79
Idea behind finding the minimum sum of product from two array is to sort both array one
in increasing and other in decreasing manner. These type of arrays will always produce
minimum sum of pair product. Sorting both array will give the pair value i.e. which
element from A is paired to which element from B[]. After that count the de-arrangement
from original arrays.
Algorithm :
549
Chapter 79. De-arrangements for minimum product sum of two arrays
550
Chapter 79. De-arrangements for minimum product sum of two arrays
Output:
Source
https://www.geeksforgeeks.org/de-arrangements-for-minimum-product-sum-of-two-arrays/
551
Chapter 80
Input : ab aa aa bcd ab
Output : 3
As aa, aa destroys each other so, ab bcd ab is the
new sequence.
Method 1:
552
Chapter 80. Delete consecutive same words in a sequence
C++
553
Chapter 80. Delete consecutive same words in a sequence
Java
554
Chapter 80. Delete consecutive same words in a sequence
{
Vector<String> v = new Vector<>();
v.addElement("tom"); v.addElement("jerry");
v.addElement("jerry");v.addElement("tom");
System.out.println(removeConsecutiveSame(v));
}
}
Output:
C++
555
Chapter 80. Delete consecutive same words in a sequence
Java
556
Chapter 80. Delete consecutive same words in a sequence
Output:
Source
https://www.geeksforgeeks.org/delete-consecutive-words-sequence/
557
Chapter 81
A simple solution is to use two loops to count frequency of every element and keep track
of maximum and minimum frequencies.
A better solution is to sort the array in O(n log n) and check
consecutive element’s occurrence and compare their count respectively.
CPP
558
Chapter 81. Difference between highest and least frequencies in an array
Java
559
Chapter 81. Difference between highest and least frequencies in an array
Python3
560
Chapter 81. Difference between highest and least frequencies in an array
C#
561
Chapter 81. Difference between highest and least frequencies in an array
}
}
return (max_count - min_count);
}
// Driver program to test above function
public static void Main()
{
int[] arr = { 7, 8, 4, 5, 4, 1,
1, 7, 7, 2, 5 };
int n = arr.Length;
Console.WriteLine(findDiff(arr, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP code to find the
// difference between highest
// and least frequencies
// function that
// returns difference
function findDiff($arr, $n)
{
// sort the array
sort($arr);
$count = 0; $max_count = 0;
$min_count = $n;
for ($i = 0; $i < ($n - 1); $i++)
{
// checking consecutive elements
if ($arr[$i] == $arr[$i + 1])
{
$count += 1;
continue;
}
else
{
562
Chapter 81. Difference between highest and least frequencies in an array
Output:
An efficient solution is to use hashing. We count frequencies of all elements and finally
traverse the hash table to find maximum and minimum.
Below is c++ implementation
563
Chapter 81. Difference between highest and least frequencies in an array
return (max_count - min_count);
}
// Driver
int main()
{
int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findDiff(arr, n) << "\n";
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/difference-between-highest-and-least-frequencies-in-an-array/
564
Chapter 82
Dual pivot quick sort is a little bit faster than the original single pivot quicksort. But still,
the worst case will remain O(n^2) when the array is already sorted in an increasing or
decreasing order.
An example:
565
Chapter 82. Dual pivot Quicksort
566
Chapter 82. Dual pivot Quicksort
DualPivotQuickSort(arr, lp + 1, rp - 1);
DualPivotQuickSort(arr, rp + 1, high);
}
}
int partition(int* arr, int low, int high, int* lp)
{
if (arr[low] > arr[high])
swap(&arr[low], &arr[high]);
// p is the left pivot, and q is the right pivot.
int j = low + 1;
int g = high - 1, k = low + 1, p = arr[low], q = arr[high];
while (k <= g) {
// if elements are less than the left pivot
if (arr[k] < p) {
swap(&arr[k], &arr[j]);
j++;
}
// if elements are greater than or equal
// to the right pivot
else if (arr[k] >= q) {
while (arr[g] > q && k < g)
g--;
swap(&arr[k], &arr[g]);
g--;
if (arr[k] < p) {
swap(&arr[k], &arr[j]);
j++;
}
}
k++;
}
j--;
g++;
// bring pivots to their appropriate positions.
swap(&arr[low], &arr[j]);
swap(&arr[high], &arr[g]);
// returning the indeces of the pivots.
*lp = j; // because we cannot return two elements
// from a function.
return g;
}
567
Chapter 82. Dual pivot Quicksort
// Driver code
int main()
{
int arr[] = { 24, 8, 42, 75, 29, 77, 38, 57 };
DualPivotQuickSort(arr, 0, 7);
printf("Sorted array: ");
for (int i = 0; i < 8; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Output:
Sorted array: 8 24 29 38 42 57 75 77
Source
https://www.geeksforgeeks.org/dual-pivot-quicksort/
568
Chapter 83
Efficiently merging two sorted arrays with O(1) extra space - GeeksforGeeks
Given two sorted arrays, we need to merge them in O((n+m)*log(n+m)) time with O(1)
extra space into a sorted array, when n is the size of the first array, and m is the size of the
second array.
Example:
569
Chapter 83. Efficiently merging two sorted arrays with O(1) extra space
C++
570
Chapter 83. Efficiently merging two sorted arrays with O(1) extra space
571
Chapter 83. Efficiently merging two sorted arrays with O(1) extra space
printf("\nSecond Array: ");
for (int i = 0; i < m; i++)
printf("%d ", a2[i]);
printf("\n");
return 0;
}
Java
572
Chapter 83. Efficiently merging two sorted arrays with O(1) extra space
{
// comparing elements in the
// second array.
for (j = 0; j + gap < m; j++)
if (arr2[j] > arr2[j + gap]) {
int temp = arr2[j];
arr2[j] = arr2[j + gap];
arr2[j+gap] = temp;
}
}
}
}
public static void main(String[] args) {
int[] a1 = { 10, 27, 38, 43 ,82 };
int[] a2 = { 3,9 };
merge(a1, a2, a1.length, a2.length);
System.out.print("First Array: ");
for (int i = 0; i < a1.length; i++) {
System.out.print(a1[i] + " ");
}
System.out.println();
System.out.print("Second Array: ");
for (int i = 0; i < a2.length; i++) {
System.out.print(a2[i] + " ");
}
}
}
// This code is contributed by Vinisha Shah
C#
573
Chapter 83. Efficiently merging two sorted arrays with O(1) extra space
574
Chapter 83. Efficiently merging two sorted arrays with O(1) extra space
merge(a1, a2, a1.Length, a2.Length);
Console.Write("First Array: ");
for (int i = 0; i < a1.Length; i++) {
Console.Write(a1[i] + " ");
}
Console.WriteLine();
Console.Write("Second Array: ");
for (int i = 0; i < a2.Length; i++) {
Console.Write(a2[i] + " ");
}
}
}
// This code is contributed by Sam007.
PHP
<?php
// Merging two sorted arrays
// with O(1) extra space
// Function to find next gap.
function nextGap($gap)
{
if ($gap <= 1)
return 0;
return ($gap / 2) +
($gap % 2);
}
function merge($arr1, $arr2,
$n, $m)
{
$i;
$j;
$gap = $n + $m;
for ($gap = nextGap($gap);
$gap > 0; $gap = nextGap($gap))
{
// comparing elements
// in the first array.
for ($i = 0; $i + $gap < $n; $i++)
if ($arr1[$i] > $arr1[$i + $gap])
{
575
Chapter 83. Efficiently merging two sorted arrays with O(1) extra space
$tmp = $arr1[$i];
$arr1[$i] = $arr1[$i + $gap];
$arr1[$i + $gap] = $tmp;
}
// comparing elements
// in both arrays.
for ($j = $gap > $n ? $gap - $n : 0 ;
$i < $n && $j < $m; $i++, $j++)
if ($arr1[$i] > $arr2[$j])
{
$tmp = $arr1[$i];
$arr1[$i] = $arr2[$j];
$arr2[$j] = $tmp;
}
if ($j < $m)
{
// comparing elements in
// the second array.
for ($j = 0; $j + $gap < $m; $j++)
if ($arr2[$j] > $arr2[$j + $gap])
{
$tmp = $arr2[$j];
$arr2[$j] = $arr2[$j + $gap];
$arr2[$j + $gap] = $tmp;
}
}
}
echo "First Array: ";
for ($i = 0; $i < $n; $i++)
echo $arr1[$i]." ";
echo "\nSecond Array: ";
for ($i = 0; $i < $m; $i++)
echo $arr2[$i] . " ";
echo"\n";
}
// Driver code
$a1 = array(10, 27, 38, 43 ,82);
$a2 = array(3,9);
$n = sizeof($a1);
$m = sizeof($a2);
merge($a1, $a2, $n, $m);
576
Chapter 83. Efficiently merging two sorted arrays with O(1) extra space
// This code is contributed
// by mits.
?>
Output:
First Array: 3 9 10 27 38
Second Array: 43 82
Source
https://www.geeksforgeeks.org/efficiently-merging-two-sorted-arrays-with-o1-extra-space/
577
Chapter 84
Input: arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }
Output: 9 4
578
Chapter 84. Elements that occurred only once in the array
Java
// Java implementation
// of above approach
import java.util.*;
579
Chapter 84. Elements that occurred only once in the array
class GFG
{
// Function to find the elements that
// appeared only once in the array
static void occurredOnce(int arr[], int n)
{
// Sort the array
Arrays.sort(arr);
// Check for first element
if (arr[0] != arr[1])
System.out.println(arr[0] + " ");
// Check for all the elements
// if it is different
// its adjacent elements
for (int i = 1; i < n - 1; i++)
if (arr[i] != arr[i + 1] &&
arr[i] != arr[i - 1])
System.out.print(arr[i] + " ");
// Check for the last element
if (arr[n - 2] != arr[n - 1])
System.out.print(arr[n - 1] + " ");
}
// Driver code
public static void main(String args[])
{
int arr[] = {7, 7, 8, 8, 9,
1, 1, 4, 2, 2};
int n = arr.length;
occurredOnce(arr, n);
}
}
// This code is contributed
// by Arnab Kundu
Python 3
# Python 3 implementation
# of above approach
# Function to find the elements
# that appeared only once in
580
Chapter 84. Elements that occurred only once in the array
# the array
def occurredOnce(arr, n):
# Sort the array
arr.sort()
# Check for first element
if arr[0] != arr[1]:
print(arr[0], end = " ")
# Check for all the elements
# if it is different its
# adjacent elements
for i in range(1, n - 1):
if (arr[i] != arr[i + 1] and
arr[i] != arr[i - 1]):
print( arr[i], end = " ")
# Check for the last element
if arr[n - 2] != arr[n - 1]:
print(arr[n - 1], end = " ")
# Driver code
if __name__ == "__main__":
arr = [ 7, 7, 8, 8, 9,
1, 1, 4, 2, 2 ]
n = len(arr)
occurredOnce(arr, n)
# This code is contributed
# by ChitraNayal
C#
// C# implementation
// of above approach
using System;
class GFG
{
// Function to find the elements that
// appeared only once in the array
static void occurredOnce(int[] arr, int n)
{
// Sort the array
Array.Sort(arr);
581
Chapter 84. Elements that occurred only once in the array
// Check for first element
if (arr[0] != arr[1])
Console.Write(arr[0] + " ");
// Check for all the elements
// if it is different
// its adjacent elements
for (int i = 1; i < n - 1; i++)
if (arr[i] != arr[i + 1] &&
arr[i] != arr[i - 1])
Console.Write(arr[i] + " ");
// Check for the last element
if (arr[n - 2] != arr[n - 1])
Console.Write(arr[n - 1] + " ");
}
// Driver code
public static void Main()
{
int[] arr = {7, 7, 8, 8, 9,
1, 1, 4, 2, 2};
int n = arr.Length;
occurredOnce(arr, n);
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// PHP implementation
// of above approach
// Function to find the elements
// that appeared only once in
// the array
function occurredOnce(&$arr, $n)
{
// Sort the array
sort($arr);
// Check for first element
if ($arr[0] != $arr[1])
582
Chapter 84. Elements that occurred only once in the array
Output:
4 9
583
Chapter 84. Elements that occurred only once in the array
// Function to find the elements that
// appeared only once in the array
void occurredOnce(int arr[], int n)
{
unordered_map<int, int> mp;
// Store all the lements int the map with
// theri occurrence
for (int i = 0; i < n; i++)
mp[arr[i]]++;
// Traverse the map and print all the
// elements with occurrence 1
for (auto it = mp.begin(); it != mp.end(); it++)
if (it->second == 1)
cout << it->first << " ";
}
// Driver code
int main()
{
int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
occurredOnce(arr, n);
return 0;
}
Output:
4 9
• Check if the first and last element is equal. If yes then start traversing the elements
between them.
• Check if the current element is equal to the element at immediate previous index. If
yes, check the same for next element.
584
Chapter 84. Elements that occurred only once in the array
C++
585
Chapter 84. Elements that occurred only once in the array
return 0;
}
Java
586
Chapter 84. Elements that occurred only once in the array
Python 3
587
Chapter 84. Elements that occurred only once in the array
# Check for the last element
if (arr[n - 1] != arr[0] and
arr[n - 1] != arr[n - 2]):
print(arr[n - 1])
# Driver code
if __name__ == "__main__":
arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ]
n = len(arr)
occurredOnce(arr, n)
# This code is contributed
# by ChitraNayal
C#
// C# implementation to find
// elements that appeared only once
using System;
class GFG
{
// Function to find the elements that
// appeared only once in the array
static void occurredOnce(int[] arr, int n)
{
int i = 1, len = n;
// Check if the first and last
// element is equal. If yes,
// remove those elements
if (arr[0] == arr[len - 1])
{
i = 2;
len--;
}
// Start traversing the
// remaining elements
for (; i < n; i++)
// Check if current element is
// equal to the element at
// immediate previous index
// If yes, check the same
// for next element
588
Chapter 84. Elements that occurred only once in the array
PHP
<?php
// PHP implementation to find
// elements that appeared only once
// Function to find the elements that
// appeared only once in the array
function occurredOnce(&$arr, $n)
{
$i = 1;
$len = $n;
// Check if the first and last
// element is equal. If yes,
// remove those elements
if ($arr[0] == $arr[$len - 1])
{
$i = 2;
$len--;
}
589
Chapter 84. Elements that occurred only once in the array
// Start traversing the
// remaining elements
for (; $i < $n; $i++)
// Check if current element is
// equal to the element at
// immediate previous index
// If yes, check the same for
// next element
if ($arr[$i] == $arr[$i - 1])
$i++;
// Else print the current element
else
echo $arr[$i - 1] . " ";
// Check for the last element
if ($arr[$n - 1] != $arr[0] &&
$arr[$n - 1] != $arr[$n - 2])
echo $arr[$n - 1];
}
// Driver code
$arr = array(7, 7, 8, 8, 9,
1, 1, 4, 2, 2);
$n = sizeof($arr);
occurredOnce($arr, $n);
// This code is contributed
// by ChitraNayal
?>
Output:
9 4
590
Chapter 84. Elements that occurred only once in the array
Source
https://www.geeksforgeeks.org/elements-that-occurred-only-once-in-the-array/
591
Chapter 85
Elements to be added so that all elements of a range are present in array - GeeksforGeeks
Given an array of size N. Let A and B be the minimum and maximum in the array respec-
tively. Task is to find how many number should be added to the given array such that all
the element in the range [A, B] occur at-least once in the array.
Examples:
Method 1 (Sorting)
1- Sort the array.
2- Compare arr[i] == arr[i+1]-1 or not. If not, update count = arr[i+1]-arr[i]-1.
3- Return count.
C++
592
Chapter 85. Elements to be added so that all elements of a range are present in array
Java
593
Chapter 85. Elements to be added so that all elements of a range are present in array
return count;
}
// Drivers code
static public void main (String[] args)
{
int []arr = { 3, 5, 8, 6 };
int n = arr.length;
System.out.println(countNum(arr, n));
}
}
// This code is contributed by vt_m.
Python3
C#
594
Chapter 85. Elements to be added so that all elements of a range are present in array
using System;
public class GFG {
// Function to count numbers to be added
static int countNum(int []arr, int n)
{
int count = 0;
// Sort the array
Array.Sort(arr);
// Check if elements are consecutive
// or not. If not, update count
for (int i = 0; i < n - 1; i++)
if (arr[i] != arr[i+1] &&
arr[i] != arr[i + 1] - 1)
count += arr[i + 1] - arr[i] - 1;
return count;
}
// Drivers code
static public void Main ()
{
int []arr = { 3, 5, 8, 6 };
int n = arr.Length;
Console.WriteLine(countNum(arr, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program for
// above implementation
// Function to count
// numbers to be added
function countNum($arr, $n)
{
$count = 0;
595
Chapter 85. Elements to be added so that all elements of a range are present in array
Output:
596
Chapter 85. Elements to be added so that all elements of a range are present in array
// Make a hash of elements
// and store minimum and maximum element
for (int i = 0; i < n; i++) {
s.insert(arr[i]);
if (arr[i] < minm)
minm = arr[i];
if (arr[i] > maxm)
maxm = arr[i];
}
// Traverse all elements from minimum
// to maximum and count if it is not
// in the hash
for (int i = minm; i <= maxm; i++)
if (s.find(arr[i]) == s.end())
count++;
return count;
}
// Drivers code
int main()
{
int arr[] = { 3, 5, 8, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << countNum(arr, n) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/elements-to-be-added-so-that-all-elements-of-a-range-are-present-in-array/
597
Chapter 86
Equally divide into two sets such that one set has maximum distinct elements - Geeks-
forGeeks
There are two processes P1 and P2, and N resources where N is an even number. There is
an array of N size and arr[i] represents the type of ith resource.There may be more then one
instance of a resource.You are to divide these resources equally between P1 and P2 such
that maximum number of distinct number of resources are allocated to P2. Print maximum
number of distinct resources allocated to P2.
Examples:
598
Chapter 86. Equally divide into two sets such that one set has maximum distinct elements
2. Find out the elements which are unique by comparing the adjacent elements of the sorted
array.suppose count holds the distinct number of resources in array.
3. Return the minimum of count and N/2.
Time complexity- O(N log N)
C++
Java
599
Chapter 86. Equally divide into two sets such that one set has maximum distinct elements
C#
600
Chapter 86. Equally divide into two sets such that one set has maximum distinct elements
// by ankita_saini
Ouput:
Improved By : ankita_saini
Source
https://www.geeksforgeeks.org/equally-divide-into-two-sets-such-that-one-set-has-maximum-distinct-elements/
601
Chapter 87
External Sorting
Inputs:
input_file : Name of input file. input.txt
output_file : Name of output file, output.txt
run_size : Size of a run (can fit in RAM)
num_ways : Number of runs to be merged
Output:
1) Read input_file such that at most 'run_size' elements
are read at a time. Do following for the every run read
in an array.
a) Sort the run using MergeSort.
602
Chapter 87. External Sorting
603
Chapter 87. External Sorting
{
harr[0] = x;
MinHeapify(0);
}
};
// Constructor: Builds a heap from a given array a[]
// of given size
MinHeap::MinHeap(MinHeapNode a[], int size)
{
heap_size = size;
harr = a; // store address of array
int i = (heap_size - 1) / 2;
while (i >= 0)
{
MinHeapify(i);
i--;
}
}
// A recursive method to heapify a subtree with root
// at given index. This method assumes that the
// subtrees are already heapified
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l].element < harr[i].element)
smallest = l;
if (r < heap_size && harr[r].element < harr[smallest].element)
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
// A utility function to swap two elements
void swap(MinHeapNode* x, MinHeapNode* y)
{
MinHeapNode temp = *x;
*x = *y;
*y = temp;
}
// Merges two subarrays of arr[].
604
Chapter 87. External Sorting
605
Chapter 87. External Sorting
int m = l + (r - l) / 2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
FILE* openFile(char* fileName, char* mode)
{
FILE* fp = fopen(fileName, mode);
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
return fp;
}
// Merges k sorted files. Names of files are assumed
// to be 1, 2, 3, ... k
void mergeFiles(char *output_file, int n, int k)
{
FILE* in[k];
for (int i = 0; i < k; i++)
{
char fileName[2];
// convert i to string
snprintf(fileName, sizeof(fileName), "%d", i);
// Open output files in read mode.
in[i] = openFile(fileName, "r");
}
// FINAL OUTPUT FILE
FILE *out = openFile(output_file, "w");
// Create a min heap with k heap nodes. Every heap node
// has first element of scratch output file
MinHeapNode* harr = new MinHeapNode[k];
int i;
for (i = 0; i < k; i++)
{
// break if no output file is empty and
// index i will be no. of input files
606
Chapter 87. External Sorting
607
Chapter 87. External Sorting
char fileName[2];
for (int i = 0; i < num_ways; i++)
{
// convert i to string
snprintf(fileName, sizeof(fileName), "%d", i);
// Open output files in write mode.
out[i] = openFile(fileName, "w");
}
// allocate a dynamic array large enough
// to accommodate runs of size run_size
int* arr = (int*)malloc(run_size * sizeof(int));
bool more_input = true;
int next_output_file = 0;
int i;
while (more_input)
{
// write run_size elements into arr from input file
for (i = 0; i < run_size; i++)
{
if (fscanf(in, "%d ", &arr[i]) != 1)
{
more_input = false;
break;
}
}
// sort array using merge sort
mergeSort(arr, 0, i - 1);
// write the records to the appropriate scratch output file
// can't assume that the loop runs to run_size
// since the last run's length may be less than run_size
for (int j = 0; j < i; j++)
fprintf(out[next_output_file], "%d ", arr[j]);
next_output_file++;
}
// close input and output files
for (int i = 0; i < num_ways; i++)
fclose(out[i]);
fclose(in);
}
608
Chapter 87. External Sorting
// For sorting data stored on disk
void externalSort(char* input_file, char *output_file,
int num_ways, int run_size)
{
// read the input file, create the initial runs,
// and assign the runs to the scratch output files
createInitialRuns(input_file, run_size, num_ways);
// Merge the runs using the K-way merging
mergeFiles(output_file, run_size, num_ways);
}
// Driver program to test above
int main()
{
// No. of Partitions of input file.
int num_ways = 10;
// The size of each partition
int run_size = 1000;
char input_file[] = "input.txt";
char output_file[] = "output.txt";
FILE* in = openFile(input_file, "w");
srand(time(NULL));
// generate input
for (int i = 0; i < num_ways * run_size; i++)
fprintf(in, "%d ", rand());
fclose(in);
externalSort(input_file, output_file, num_ways,
run_size);
return 0;
}
This code won’t work on online compiler as it requires file creation permissions. When run
local machine, it produces sample input file “input.txt” with 10000 random numbers. It
sorts the numbers and puts the sorted numbers in a file “output.txt”. It also generates files
with names 1, 2, .. to store sorted runs.
References :
https://en.wikipedia.org/wiki/External_sorting
609
Chapter 87. External Sorting
http://web.eecs.utk.edu/~leparker/Courses/CS302-Fall06/Notes/external-sorting2.html
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/external-sorting/
610
Chapter 88
Find Sum of all unique sub-array sum for a given array. - GeeksforGeeks
Given an array of n-positive elements. Sub-array sum is defined as the sum of all elements
of a particular sub-array, the task is to find the sum of all unique sub-array sum.
Note: Unique Sub-array sum means no other sub-array will have the same sum value.
Examples:
611
Chapter 88. Find Sum of all unique sub-array sum for a given array.
612
Chapter 88. Find Sum of all unique sub-array sum for a given array.
Output:
41
Method 2 (Hashing Based) The idea is make an empty hash table. We generate all
subarrays. For every subarray, we compute its sum and increment count of sum in hash
table. Finally we add all those sums whose count is 1.
613
Chapter 88. Find Sum of all unique sub-array sum for a given array.
Output:
41
Source
https://www.geeksforgeeks.org/find-sum-unique-sub-array-sum-given-array/
614
Chapter 89
Input: [2, 7, 5, 3, 0, 8, 1]
Output: [4, 1, 1, 1, 2, 0, 0]
Method 1 (Naive)
The naive solution would be to run two loops. For each element of the array, we count all
elements greater than it to its right. The complexity of this solution is O(n2 )
C++
615
Chapter 89. Find Surpasser Count of each element in array
Java
616
Chapter 89. Find Surpasser Count of each element in array
{
// stores surpasser count for
// element arr[i]
int count = 0;
for (int j = i + 1; j < n; j++)
if (arr[j] > arr[i])
count++;
System.out.print(count +" ");
}
}
/* Function to print an array */
static void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
System.out.print( arr[i] + " ");
System.out.println();
}
// Driver program to test above functions
public static void main (String[] args)
{
int arr[] = { 2, 7, 5, 3, 0, 8, 1 };
int n = arr.length;
System.out.println("Given array is ");
printArray(arr, n);
System.out.println("Surpasser Count of"
+ " array is ");
findSurpasser(arr, n);
}
}
// This code is contributed by Anuj_67.
Python3
617
Chapter 89. Find Surpasser Count of each element in array
C#
618
Chapter 89. Find Surpasser Count of each element in array
int count = 0;
for (int j = i + 1; j < n; j++)
if (arr[j] > arr[i])
count++;
Console.Write(count + " ");
}
}
/* Function to print an array */
static void printArray(int []arr, int n)
{
for (int i = 0; i < n; i++)
Console.Write( arr[i] + " ");
Console.WriteLine();
}
// Driver program to test above functions
public static void Main ()
{
int []arr = { 2, 7, 5, 3, 0, 8, 1 };
int n = arr.Length;
Console.WriteLine("Given array is ");
printArray(arr, n);
Console.WriteLine("Surpasser Count of"
+ " array is ");
findSurpasser(arr, n);
}
}
// This code is contributed by Anuj_67.
PHP
<?php
// Naive PHP program to find
// surpasser count of each
// element in array
// Function to find surpasser
// count of each element in array
function findSurpasser($arr, $n)
{
for ( $i = 0; $i < $n; $i++)
{
619
Chapter 89. Find Surpasser Count of each element in array
Output :
Given array is
2 7 5 3 0 8 1
Surpasser Count of array is
4 1 1 1 2 0 0
620
Chapter 89. Find Surpasser Count of each element in array
We have already discussed how to find inversion count of complete array here. We have
modified the discussed approach to find number of inversions for each element of the array
instead of returning inversion count of whole array. Also, as all elements of the array are
distinct, we maintain a map that stores inversion count for each element of the array.
Below is C++ implementation of above idea –
C++
621
Chapter 89. Find Surpasser Count of each element in array
}
}
/* Copy the remaining elements of L[], if
there are any */
while (i < n1)
{
hm[L[i]] += c;
arr[k++] = L[i++];
}
/* Copy the remaining elements of R[], if
there are any */
while (j < n2)
arr[k++] = R[j++];
}
/* l is for left index and r is right index of
the sub-array of arr to be sorted */
int mergeSort(int arr[], int l, int r,
unordered_map<int, int> &hm)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m, hm);
mergeSort(arr, m + 1, r, hm);
merge(arr, l, m, r, hm);
}
}
/* Function to print an array */
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
void findSurpasser(int arr[], int n)
{
// To store inversion count for elements
unordered_map<int, int> hm;
// To store copy of array
int dup[n];
memcpy(dup, arr, n*sizeof(arr[0]));
622
Chapter 89. Find Surpasser Count of each element in array
Output :
Given array is
2 7 5 3 0 8 1
Surpasser Count of array is
4 1 1 1 2 0 0
Source
https://www.geeksforgeeks.org/find-surpasser-count-of-each-element-in-array/
623
Chapter 90
Find a pair of elements swapping which makes sum of two arrays same - GeeksforGeeks
Given two arrays of integers, find a pair of values (one value from each array) that you can
swap to give the two arrays the same sum.
Examples:
624
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
625
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
Java
626
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
int n = A.length;
int B[] = { 3, 6, 3, 3 };
int m = B.length;
// Call to function
findSwapValues(A, n, B, m);
}
}
// Contributed by Pramod Kumar
Python
627
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
Output :
1 3
Therefore, we’re looking for two values that have a specific target difference: (sumA – sumB)
/ 2.
C/C++
628
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
}
// Function to calculate : a - b = (sumA - sumB) / 2
int getTarget(int A[], int n, int B[], int m)
{
// Calculation of sums from both arrays
int sum1 = getSum(A, n);
int sum2 = getSum(B, m);
// because that the target must be an integer
if ((sum1 - sum2) % 2 != 0)
return 0;
return ((sum1 - sum2) / 2);
}
void findSwapValues(int A[], int n, int B[], int m)
{
int target = getTarget(A, n, B, m);
if (target == 0)
return;
// Look for val1 and val2, such that
// val1 - val2 = (sumA - sumB) / 2
int val1, val2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (A[i] - B[j] == target) {
val1 = A[i];
val2 = B[j];
}
}
}
cout << val1 << " " << val2;
}
// Driver code
int main()
{
int A[] = { 4, 1, 2, 1, 1, 2 };
int n = sizeof(A) / sizeof(A[0]);
int B[] = { 3, 6, 3, 3 };
int m = sizeof(B) / sizeof(B[0]);
// Call to function
findSwapValues(A, n, B, m);
return 0;
}
629
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
Java
630
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
}
}
}
System.out.println(val1+" "+val2);
}
// driver program
public static void main (String[] args)
{
int A[] = { 4, 1, 2, 1, 1, 2 };
int n = A.length;
int B[] = { 3, 6, 3, 3 };
int m = B.length;
// Call to function
findSwapValues(A, n, B, m);
}
}
// Contributed by Pramod Kumar
Python
631
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
return
# Boolean variable used to reduce further iterations
# after the pair is found
flag=False
# Look for val1 and val2, such that
# val1 - val2 = (sumA -sumB) /2
val1,val2=0,0
for i in A:
for j in B:
if i-j == target:
val1=i
val2=j
# Set to True when pair is found
flag=True
break
if flag==True:
break
print val1,val2
return
# Driver code
A=[4,1,2,1,1,2]
B=[3,6,3,3]
# Call to function
findSwapValues(A,B)
# code contributed by sachin bisht
Output:
1 3
632
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
bigger value.
b) If it is too big then, make it smaller
by moving b to a bigger value.
c) If it's just right, return this pair.
C/C++
633
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
int i = 0, j = 0;
while (i < n && j < m) {
int diff = A[i] - B[j];
if (diff == target) {
cout << A[i] << " " << B[j];
return;
}
// Look for a greater value in A[]
else if (diff < target)
i++;
// Look for a greater value in B[]
else
j++;
}
}
// Driver code
int main()
{
int A[] = { 4, 1, 2, 1, 1, 2 };
int n = sizeof(A) / sizeof(A[0]);
int B[] = { 1, 6, 3, 3 };
int m = sizeof(B) / sizeof(B[0]);
findSwapValues(A, n, B, m);
return 0;
}
Java
634
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
635
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
Python
636
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
return
i,j=0,0
while(i<len(A) and j<len(B)):
diff=A[i]-B[j]
if diff == target:
print A[i],B[j]
return
# Look for a greater value in list A
elif diff <target:
i+=1
# Look for a greater value in list B
else:
j+=1
A=[4,1,2,1,1,2]
B=[3,6,3,3]
findSwapValues(A,B)
#code contibuted by sachin bisht
Output:
2 3
Time Complexity :-
If arrays are sorted : O(n + m)
If arrays aren’t sorted : O(nlog(n) + mlog(m))
Method 4 (Hashing)
We can solve this problem in O(m+n) time and O(m) auxiliary space. Below are algorith-
mic steps.
637
Chapter 90. Find a pair of elements swapping which makes sum of two arrays same
Source
https://www.geeksforgeeks.org/find-a-pair-swapping-which-makes-sum-of-two-arrays-same/
638
Chapter 91
A Simple Solution is to consider every pair and keep track maximum product. Below is
the implementation of this simple solution.
C++
639
Chapter 91. Find a pair with maximum product in array of Integers
}
// Initialize max product pair
int a = arr[0], b = arr[1];
// Traverse through every possible pair
// and keep track of max product
for (int i=0; i<n; i++)
for (int j=i+1; j<n; j++)
if (arr[i]*arr[j] > a*b)
a = arr[i], b = arr[j];
cout << "Max product pair is {" << a << ", "
<< b << "}";
}
// Driver program to test
int main()
{
int arr[] = {1, 4, 3, 6, 7, 0};
int n = sizeof(arr)/sizeof(arr[0]);
maxProduct(arr, n);
return 0;
}
Java
640
Chapter 91. Find a pair with maximum product in array of Integers
Python3
641
Chapter 91. Find a pair with maximum product in array of Integers
sep = "")
# Driver Code
arr = [1, 4, 3, 6, 7, 0]
n = len(arr)
maxProduct(arr, n)
# This code is contributed by Smitha Dinesh Semwal.
C#
642
Chapter 91. Find a pair with maximum product in array of Integers
PHP
<?php
// A simple PHP program to
// find max product pair in
// an array of integers
// Function to find maximum
// product pair in arr[0..n-1]
function maxProduct( $arr, $n)
{
if ($n < 2)
{
echo "No pairs exists\n";
return;
}
// Initialize max product pair
$a = $arr[0];
$b = $arr[1];
// Traverse through every possible pair
// and keep track of max product
for ($i = 0; $i < $n; $i++)
for ($j = $i + 1; $j < $n; $j++)
{
if ($arr[$i] * $arr[$j] > $a * $b)
{
$a = $arr[$i];
$b = $arr[$j];
}
}
echo "Max product pair is {" , $a , ", ";
echo $b , "}";
}
// Driver Code
$arr = array(1, 4, 3, 6, 7, 0);
$n = count($arr);
643
Chapter 91. Find a pair with maximum product in array of Integers
maxProduct($arr, $n);
// This code is contributed by anuj_67.
?>
Output :
644
Chapter 91. Find a pair with maximum product in array of Integers
// Iniitialize maximum and second maximum
int posa = INT_MIN, posb = INT_MIN;
// Iniitialize minimum and second minimum
int nega = INT_MIN, negb = INT_MIN;
// Traverse given array
for (int i = 0; i < n; i++)
{
// Update maximum and second maximum if needed
if (arr[i] > posa)
{
posb = posa;
posa = arr[i];
}
else if (arr[i] > posb)
posb = arr[i];
// Update minimum and second minimum if needed
if (arr[i] < 0 && abs(arr[i]) > abs(nega))
{
negb = nega;
nega = arr[i];
}
else if(arr[i] < 0 && abs(arr[i]) > abs(negb))
negb = arr[i];
}
if (nega*negb > posa*posb)
cout << "Max product pair is {" << nega << ", "
<< negb << "}";
else
cout << "Max product pair is {" << posa << ", "
<< posb << "}";
}
// Driver program to test above function
int main()
{
int arr[] = {1, 4, 3, 6, 7, 0};
int n = sizeof(arr)/sizeof(arr[0]);
maxProduct(arr, n);
return 0;
}
Java
645
Chapter 91. Find a pair with maximum product in array of Integers
646
Chapter 91. Find a pair with maximum product in array of Integers
negb = nega;
nega = arr[i];
}
else if(arr[i] < 0 && Math.abs(arr[i])
> Math.abs(negb))
negb = arr[i];
}
if (nega * negb > posa * posb)
System.out.println("Max product pair is {"
+ nega + ", " + negb + "}");
else
System.out.println("Max product pair is {"
+ posa + ", " + posb + "}");
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {1, 4, 3, 6, 7, 0};
int n = arr.length;
maxProduct(arr, n);
}
}
// This code is contributed by Arnav Kr. Mandal.
C#
647
Chapter 91. Find a pair with maximum product in array of Integers
return;
}
// Iniitialize maximum and
// second maximum
int posa = int.MinValue;
int posb = int.MaxValue;
// Iniitialize minimum and
// second minimum
int nega = int.MinValue;
int negb = int.MaxValue;
// Traverse given array
for (int i = 0; i < n; i++)
{
// Update maximum and
// second maximum
// if needed
if (arr[i] > posa)
{
posb = posa;
posa = arr[i];
}
else if (arr[i] > posb)
posb = arr[i];
// Update minimum and
// second minimum if
// needed
if (arr[i] < 0 && Math.Abs(arr[i]) >
Math.Abs(nega))
{
negb = nega;
nega = arr[i];
}
else if(arr[i] < 0 &&
Math.Abs(arr[i]) >
Math.Abs(negb))
negb = arr[i];
}
if (nega * negb > posa * posb)
Console.WriteLine("Max product pair is {"
+ nega + ", " + negb + "}");
else
Console.WriteLine("Max product pair is {"
648
Chapter 91. Find a pair with maximum product in array of Integers
Output:
Source
https://www.geeksforgeeks.org/return-a-pair-with-maximum-product-in-array-of-integers/
649
Chapter 92
Examples:
Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78
Output: Pair Found: (2, 80)
The simplest method is to run two loops, the outer loop picks the first element (smaller
element) and the inner loop looks for the element picked by outer loop plus n. Time
complexity of this method is O(n^2).
We can use sorting and Binary Search to improve time complexity to O(nLogn). The first
step is to sort the array in ascending order. Once the array is sorted, traverse the array
from left to right, and for each element arr[i], binary search for arr[i] + n in arr[i+1..n-1]. If
the element is found, return the pair.
Both first and second steps take O(nLogn). So overall complexity is O(nLogn).
The second step of the above algorithm can be improved to O(n). The first step remain
same. The idea for second step is take two index variables i and j, initialize them as 0 and
1 respectively. Now run a linear loop. If arr[j] – arr[i] is smaller than n, we need to look for
greater arr[j], so increment j. If arr[j] – arr[i] is greater than n, we need to look for greater
arr[i], so increment i. Thanks to Aashish Barnwal for suggesting this approach.
The following code is only for the second step of the algorithm, it assumes that the array is
already sorted.
C/C++
650
Chapter 92. Find a pair with the given difference
Java
651
Chapter 92. Find a pair with the given difference
Python
652
Chapter 92. Find a pair with the given difference
if i != j and arr[j]-arr[i] == n:
print "Pair found (",arr[i],",",arr[j],")"
return True
elif arr[j] - arr[i] < n:
j+=1
else:
i+=1
print "No pair found"
return False
# Driver function to test above function
arr = [1, 8, 30, 40, 100]
n = 60
findPair(arr, n)
# This code is contributed by Devesh Agrawal
C#
653
Chapter 92. Find a pair with the given difference
}
Console.Write("No such pair");
return false;
}
// Driver program to test above function
public static void Main ()
{
int []arr = {1, 8, 30, 40, 100};
int n = 60;
findPair(arr, n);
}
}
// This code is contributed by Sam007.
Output:
Hashing can also be used to solve this problem. Create an empty hash table HT. Traverse
the array, use array elements as hash keys and enter them in HT. Traverse the array again
look for value n + arr[i] in HT.
Source
https://www.geeksforgeeks.org/find-a-pair-with-the-given-difference/
654
Chapter 93
Now how to get worst case input for merge sort for an input set?
Lets us try to build the array in bottom up manner
Let the sorted array be {1,2,3,4,5,6,7,8}.
655
Chapter 93. Find a permutation that causes worst case of Merge Sort
In order to generate the worst case of merge sort, the merge operation that resulted in above
sorted array should result in maximum comparisons. In order to do so, the left and right sub-
array involved in merge operation should store alternate elements of sorted array. i.e. left
sub-array should be {1,3,5,7} and right sub-array should be {2,4,6,8}. Now every element
of array will be compared at-least once and that will result in maximum comparisons. We
apply the same logic for left and right sub-array as well. For array {1,3,5,7}, the worst
case will be when its left and right sub-array are {1,5} and {3,7} respectively and for array
{2,4,6,8} the worst case will occur for {2,4} and {6,8}.
Complete Algorithm –
GenerateWorstCase(arr[])
1. 1. Create two auxillary arrays left and right and store alternate array elements in
them.
2. Call GenerateWorstCase for left subarray: GenerateWorstCase (left)
3. Call GenerateWorstCase for right subarray: GenerateWorstCase (right)
4. Copy all elements of left and right subarrays back to original array.
656
Chapter 93. Find a permutation that causes worst case of Merge Sort
// Function to store alternate elemets in left
// and right subarray
int split(int arr[], int left[], int right[],
int l, int m, int r)
{
for (int i = 0; i <= m - l; i++)
left[i] = arr[i * 2];
for (int i = 0; i < r - m; i++)
right[i] = arr[i * 2 + 1];
}
// Function to generate Worst Case of Merge Sort
int generateWorstCase(int arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
// create two auxillary arrays
int left[m - l + 1];
int right[r - m];
// Store alternate array elements in left
// and right subarray
split(arr, left, right, l, m, r);
// Recurse first and second halves
generateWorstCase(left, l, m);
generateWorstCase(right, m + 1, r);
// join left and right subarray
join(arr, left, right, l, m, r);
}
}
// Driver code
int main()
{
// Sorted array
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Sorted array is \n");
printArray(arr, n);
657
Chapter 93. Find a permutation that causes worst case of Merge Sort
Java
658
Chapter 93. Find a permutation that causes worst case of Merge Sort
// create two auxillary arrays
int[] left = new int[m - l + 1];
int[] right = new int[r - m];
// Store alternate array elements in left
// and right subarray
split(arr, left, right, l, m, r);
// Recurse first and second halves
generateWorstCase(left, l, m);
generateWorstCase(right, m + 1, r);
// join left and right subarray
join(arr, left, right, l, m, r);
}
}
// driver program
public static void main (String[] args)
{
// sorted array
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16 };
int n = arr.length;
System.out.println("Sorted array is");
System.out.println(Arrays.toString(arr));
// generate Worst Case of Merge Sort
generateWorstCase(arr, 0, n - 1);
System.out.println("\nInput array that will result in \n"+
"worst case of merge sort is \n");
System.out.println(Arrays.toString(arr));
}
}
// Contributed by Pramod Kumar
C#
659
Chapter 93. Find a permutation that causes worst case of Merge Sort
660
Chapter 93. Find a permutation that causes worst case of Merge Sort
}
// driver program
public static void Main ()
{
// sorted array
int []arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16 };
int n = arr.Length;
Console.Write("Sorted array is\n");
for(int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
// generate Worst Case of Merge Sort
generateWorstCase(arr, 0, n - 1);
Console.Write("\nInput array that will "
+ "result in \n worst case of"
+ " merge sort is \n");
for(int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Smitha
Output:
Sorted array is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
661
Chapter 93. Find a permutation that causes worst case of Merge Sort
Source
https://www.geeksforgeeks.org/find-a-permutation-that-causes-worst-case-of-merge-sort/
662
Chapter 94
#include <stdio.h>
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
int l, r;
// Fix the first element as A[i]
for (int i = 0; i < arr_size - 2; i++) {
// Fix the second element as A[j]
for (int j = i + 1; j < arr_size - 1; j++) {
// Now look for the third number
for (int k = j + 1; k < arr_size; k++) {
if (A[i] + A[j] + A[k] == sum) {
663
Chapter 94. Find a triplet that sum to a given value
Java
class FindTriplet {
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
boolean find3Numbers(int A[], int arr_size, int sum)
{
int l, r;
// Fix the first element as A[i]
for (int i = 0; i < arr_size - 2; i++) {
// Fix the second element as A[j]
for (int j = i + 1; j < arr_size - 1; j++) {
// Now look for the third number
for (int k = j + 1; k < arr_size; k++) {
if (A[i] + A[j] + A[k] == sum) {
System.out.print("Triplet is " + A[i] +
", " + A[j] + ", " + A[k]);
return true;
}
}
}
}
664
Chapter 94. Find a triplet that sum to a given value
// If we reach here, then no triplet was found
return false;
}
// Driver program to test above functions
public static void main(String[] args)
{
FindTriplet triplet = new FindTriplet();
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = A.length;
triplet.find3Numbers(A, arr_size, sum);
}
}
Python3
665
Chapter 94. Find a triplet that sum to a given value
C#
666
Chapter 94. Find a triplet that sum to a given value
PHP
<?php
// PHP program to find a triplet
// that sum to a given value
// returns true if there is
// triplet with sum equal to
// 'sum' present in A[].
// Also, prints the triplet
function find3Numbers($A, $arr_size, $sum)
{
$l; $r;
// Fix the first
// element as A[i]
for ($i = 0;
$i < $arr_size - 2; $i++)
{
// Fix the second
// element as A[j]
for ($j = $i + 1;
$j < $arr_size - 1; $j++)
{
// Now look for the
// third number
for ($k = $j + 1;
$k < $arr_size; $k++)
{
if ($A[$i] + $A[$j] +
667
Chapter 94. Find a triplet that sum to a given value
$A[$k] == $sum)
{
echo "Triplet is", " ", $A[$i],
", ", $A[$j],
", ", $A[$k];
return true;
}
}
}
}
// If we reach here, then
// no triplet was found
return false;
}
// Driver Code
$A = array(1, 4, 45,
6, 10, 8);
$sum = 22;
$arr_size = sizeof($A);
find3Numbers($A, $arr_size, $sum);
// This code is contributed by ajit
?>
Output :
Triplet is 4, 10, 8
668
Chapter 94. Find a triplet that sum to a given value
{
int l, r;
/* Sort the elements */
sort(A, A + arr_size);
/* Now fix the first element one by one and find the
other two elements */
for (int i = 0; i < arr_size - 2; i++) {
// To find the other two elements, start two index
// variables from two corners of the array and move
// them toward each other
l = i + 1; // index of the first element in the
// remaining elements
r = arr_size - 1; // index of the last element
while (l < r) {
if (A[i] + A[l] + A[r] == sum) {
printf("Triplet is %d, %d, %d", A[i],
A[l], A[r]);
return true;
}
else if (A[i] + A[l] + A[r] < sum)
l++;
else // A[i] + A[l] + A[r] > sum
r--;
}
}
// If we reach here, then no triplet was found
return false;
}
/* Driver program to test above function */
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = sizeof(A) / sizeof(A[0]);
find3Numbers(A, arr_size, sum);
return 0;
}
Java
669
Chapter 94. Find a triplet that sum to a given value
class FindTriplet {
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
boolean find3Numbers(int A[], int arr_size, int sum)
{
int l, r;
/* Sort the elements */
quickSort(A, 0, arr_size - 1);
/* Now fix the first element one by one and find the
other two elements */
for (int i = 0; i < arr_size - 2; i++) {
// To find the other two elements, start two index variables
// from two corners of the array and move them toward each
// other
l = i + 1; // index of the first element in the remaining elements
r = arr_size - 1; // index of the last element
while (l < r) {
if (A[i] + A[l] + A[r] == sum) {
System.out.print("Triplet is " + A[i] +
", " + A[l] + ", " + A[r]);
return true;
}
else if (A[i] + A[l] + A[r] < sum)
l++;
else // A[i] + A[l] + A[r] > sum
r--;
}
}
// If we reach here, then no triplet was found
return false;
}
int partition(int A[], int si, int ei)
{
int x = A[ei];
int i = (si - 1);
int j;
for (j = si; j <= ei - 1; j++) {
if (A[j] <= x) {
i++;
int temp = A[i];
670
Chapter 94. Find a triplet that sum to a given value
A[i] = A[j];
A[j] = temp;
}
}
int temp = A[i + 1];
A[i + 1] = A[ei];
A[ei] = temp;
return (i + 1);
}
/* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
void quickSort(int A[], int si, int ei)
{
int pi;
/* Partitioning index */
if (si < ei) {
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
// Driver program to test above functions
public static void main(String[] args)
{
FindTriplet triplet = new FindTriplet();
int A[] = { 1, 4, 45, 6, 10, 8 };
int sum = 22;
int arr_size = A.length;
triplet.find3Numbers(A, arr_size, sum);
}
}
Python3
671
Chapter 94. Find a triplet that sum to a given value
C#
672
Chapter 94. Find a triplet that sum to a given value
using System;
class GFG
{
// returns true if there is triplet
// with sum equal to 'sum' present
// in A[]. Also, prints the triplet
bool find3Numbers(int[] A, int arr_size,
int sum)
{
int l, r;
/* Sort the elements */
quickSort(A, 0, arr_size - 1);
/* Now fix the first element
one by one and find the
other two elements */
for (int i = 0; i < arr_size - 2; i++)
{
// To find the other two elements,
// start two index variables from
// two corners of the array and
// move them toward each other
l = i + 1; // index of the first element
// in the remaining elements
r = arr_size - 1; // index of the last element
while (l < r)
{
if (A[i] + A[l] + A[r] == sum)
{
Console.Write("Triplet is " + A[i] +
", " + A[l] + ", " + A[r]);
return true;
}
else if (A[i] + A[l] + A[r] < sum)
l++;
else // A[i] + A[l] + A[r] > sum
r--;
}
}
// If we reach here, then
// no triplet was found
return false;
673
Chapter 94. Find a triplet that sum to a given value
}
int partition(int[] A, int si, int ei)
{
int x = A[ei];
int i = (si - 1);
int j;
for (j = si; j <= ei - 1; j++)
{
if (A[j] <= x)
{
i++;
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
int temp1 = A[i + 1];
A[i + 1] = A[ei];
A[ei] = temp1;
return (i + 1);
}
/* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
void quickSort(int[] A, int si, int ei)
{
int pi;
/* Partitioning index */
if (si < ei)
{
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
// Driver Code
static void Main()
{
GFG triplet = new GFG();
int[] A = new int[] { 1, 4, 45, 6, 10, 8 };
int sum = 22;
674
Chapter 94. Find a triplet that sum to a given value
PHP
<?php
// PHP program to find a triplet
// returns true if there is
// triplet with sum equal to
// 'sum' present in A[]. Also,
// prints the triplet
function find3Numbers($A, $arr_size, $sum)
{
$l; $r;
/* Sort the elements */
sort($A);
/* Now fix the first element
one by one and find the
other two elements */
for ($i = 0; $i < $arr_size - 2; $i++)
{
// To find the other two elements,
// start two index variables from
// two corners of the array and
// move them toward each other
$l = $i + 1; // index of the first element
// in the remaining elements
// index of the last element
$r = $arr_size - 1;
while ($l < $r)
{
if ($A[$i] + $A[$l] +
$A[$r] == $sum)
{
echo "Triplet is ", $A[$i], " ",
$A[$l], " ",
$A[$r],"\n";
return true;
675
Chapter 94. Find a triplet that sum to a given value
}
else if ($A[$i] + $A[$l] +
$A[$r] < $sum)
$l++;
else // A[i] + A[l] + A[r] > sum
$r--;
}
}
// If we reach here, then
// no triplet was found
return false;
}
// Driver Code
$A = array (1, 4, 45, 6, 10, 8);
$sum = 22;
$arr_size = sizeof($A);
find3Numbers($A, $arr_size, $sum);
// This code is contributed by ajit
?>
Output :
Triplet is 4, 8, 10
#include <bits/stdc++.h>
using namespace std;
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
// Fix the first element as A[i]
for (int i = 0; i < arr_size - 2; i++) {
// Find pair in subarray A[i+1..n-1]
// with sum equal to sum - A[i]
unordered_set<int> s;
int curr_sum = sum - A[i];
676
Chapter 94. Find a triplet that sum to a given value
Source
https://www.geeksforgeeks.org/find-a-triplet-that-sum-to-a-given-value/
677
Chapter 95
678
Chapter 95. Find all triplets with zero sum
Java
679
Chapter 95. Find all triplets with zero sum
System.out.print(" ");
System.out.print(arr[k]);
System.out.print("\n");
found = true;
}
}
}
}
// If no triplet with 0 sum found in array
if (found == false)
System.out.println(" not exist ");
}
// Driver code
public static void main(String[] args)
{
int arr[] = {0, -1, 2, -3, 1};
int n =arr.length;
findTriplets(arr, n);
}
}
//This code is contributed by
//Smitha Dinesh Semwal
Python3
680
Chapter 95. Find all triplets with zero sum
# If no triplet with 0 sum
# found in array
if (found == False):
print(" not exist ")
# Driver code
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
# This code is contributed by Smitha Dinesh Semwal
C#
681
Chapter 95. Find all triplets with zero sum
PHP
<?php
// A simple PHP program to
// find three elements whose
// sum is equal to zero
// Prints all triplets
// in arr[] with 0 sum
function findTriplets($arr, $n)
{
$found = true;
for ($i = 0; $i < $n - 2; $i++)
{
for ($j = $i + 1; $j < $n - 1; $j++)
{
for ($k = $j + 1; $k < $n; $k++)
{
if ($arr[$i] + $arr[$j] +
$arr[$k] == 0)
{
echo $arr[$i] , " ",
$arr[$j] , " ",
$arr[$k] ,"\n";
$found = true;
}
}
}
}
// If no triplet with 0
// sum found in array
if ($found == false)
682
Chapter 95. Find all triplets with zero sum
0 -1 1
2 -3 1
C++
683
Chapter 95. Find all triplets with zero sum
// "-arr[i]"
unordered_set<int> s;
for (int j=i+1; j<n; j++)
{
int x = -(arr[i] + arr[j]);
if (s.find(x) != s.end())
{
printf("%d %d %d\n", x, arr[i], arr[j]);
found = true;
}
else
s.insert(arr[j]);
}
}
if (found == false)
cout << " No Triplet Found" << endl;
}
// Driver code
int main()
{
int arr[] = {0, -1, 2, -3, 1};
int n = sizeof(arr)/sizeof(arr[0]);
findTriplets(arr, n);
return 0;
}
-1 0 1
-3 2 1
684
Chapter 95. Find all triplets with zero sum
C++
685
Chapter 95. Find all triplets with zero sum
Python3
686
Chapter 95. Find all triplets with zero sum
PHP
<?php
// PHP program to find
// triplets in a given
// array whose sum is zero
// function to print
// triplets with 0 sum
function findTriplets($arr, $n)
{
$found = false;
// sort array elements
sort($arr);
for ($i = 0; $i < $n - 1; $i++)
{
// initialize left
// and right
$l = $i + 1;
$r = $n - 1;
$x = $arr[$i];
while ($l < $r)
{
if ($x + $arr[$l] +
$arr[$r] == 0)
{
// print elements if
// it's sum is zero
echo $x," ", $arr[$l],
" ", $arr[$r], "\n";
$l++;
687
Chapter 95. Find all triplets with zero sum
$r--;
$found = true;
}
// If sum of three elements
// is less than zero then
// increment in left
else if ($x + $arr[$l] +
$arr[$r] < 0)
$l++;
// if sum is greater than
// zero than decrement
// in right side
else
$r--;
}
}
if ($found == false)
echo " No Triplet Found" ,"\n";
}
// Driver Code
$arr = array (0, -1, 2, -3, 1);
$n = sizeof($arr);
findTriplets($arr, $n);
// This code is contributed by ajit
?>
Output :
-3 1 2
-1 0 1
688
Chapter 95. Find all triplets with zero sum
Source
https://www.geeksforgeeks.org/find-triplets-array-whose-sum-equal-zero/
689
Chapter 96
Find all elements in array which have at-least two greater elements - GeeksforGeeks
Given an array of n distinct elements, the task is to find all elements in array which have
at-least two greater elements than themselves.
Examples :
Method 1 (Simple)
The naive approach is to run two loops and check one by one element of array check that
array elements have at-least two elements greater than itself or not. If its true then print
array element.
C++
690
Chapter 96. Find all elements in array which have at-least two greater elements
Java
691
Chapter 96. Find all elements in array which have at-least two greater elements
Python3
692
Chapter 96. Find all elements in array which have at-least two greater elements
C#
693
Chapter 96. Find all elements in array which have at-least two greater elements
PHP
<?php
// Simple PHP program to find
// all elements in array which
// have at-least two greater
// elements itself.
function findElements($arr, $n)
{
// Pick elements one by one and
// count greater elements. If
// count is more than 2,
// print that element.
for ($i = 0; $i < $n; $i++)
{
$count = 0;
for ($j = 0; $j < $n; $j++)
if ($arr[$j] > $arr[$i])
$count++;
if ($count >= 2)
echo $arr[$i]." ";
}
}
// Driver code
$arr = array( 2, -6 ,3 , 5, 1);
$n = sizeof($arr);
findElements($arr, $n);
?>
Output :
2 -6 1
694
Chapter 96. Find all elements in array which have at-least two greater elements
Java
695
Chapter 96. Find all elements in array which have at-least two greater elements
findElements(arr, n);
}
}
// This code is contributed by Sahil_Bansall
Python3
Output :
-6 1 2
C#
696
Chapter 96. Find all elements in array which have at-least two greater elements
for (int i = 0; i < n-2; i++)
Console.Write(arr[i] + " ");
}
// Driver code
public static void Main(String []args)
{
int []arr = { 2, -6 ,3 , 5, 1};
int n = arr.Length;
findElements(arr, n);
}
}
// This code is contributed by parashar
PHP
<?php
// Sorting based PHP program to
// find all elements in array
// which have atleast two greater
// elements itself.
function findElements( $arr, $n)
{
sort($arr);
for ($i = 0; $i < $n - 2; $i++)
echo $arr[$i] , " ";
}
// Driver Code
$arr = array( 2, -6 ,3 , 5, 1);
$n = count($arr);
findElements($arr, $n);
// This code is contributed by anuj_67.
?>;
Output :
-6 1 2
697
Chapter 96. Find all elements in array which have at-least two greater elements
Method 3 (Efficient)
In second method we simply calculate second maximum element of array and print all
element which is less than or equal to second maximum.
C++
Java
698
Chapter 96. Find all elements in array which have at-least two greater elements
Python3
699
Chapter 96. Find all elements in array which have at-least two greater elements
C#
700
Chapter 96. Find all elements in array which have at-least two greater elements
int n)
{
int first = int.MinValue;
int second = int.MaxValue;
for (int i = 0; i < n; i++)
{
// If current element is smaller
// than first then update both
// first and second
if (arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between
first and second
then update second */
else if (arr[i] > second)
second = arr[i];
}
for (int i = 0; i < n; i++)
if (arr[i] < second)
Console.Write(arr[i] + " ") ;
}
// Driver code
public static void Main(String []args)
{
int []arr = { 2, -6, 3, 5, 1};
int n = arr.Length;
findElements(arr, n);
}
}
// This code is contributed by parashar...
PHP
<?php
// PHP program to find all elements
// in array which have atleast two
// greater elements itself.
function findElements($arr, $n)
{
701
Chapter 96. Find all elements in array which have at-least two greater elements
$first = PHP_INT_MIN;
$second = PHP_INT_MIN;
for ($i = 0; $i < $n; $i++)
{
/* If current element is smaller
than first then update both first
and second */
if ($arr[$i] > $first)
{
$second = $first;
$first = $arr[$i];
}
/* If arr[i] is in between first
and second then update second */
else if ($arr[$i] > $second)
$second = $arr[$i];
}
for($i = 0; $i < $n; $i++)
if ($arr[$i] < $second)
echo $arr[$i] , " ";
}
// Driver code
$arr = array(2, -6, 3, 5, 1);
$n = count($arr);
findElements($arr, $n);
// This code is contributed by vishal tripathi.
?>
Output :
2 -6 1
Source
https://www.geeksforgeeks.org/find-elements-array-least-two-greater-elements/
702
Chapter 97
Input : n = 3
k = 3
Output : a[] = {2, 1, 3}
Explanation:
Here, a[] = {2, 1, 3}
First of all, mergesort(0, 3) will be called,
which then sets mid = 1 and calls mergesort(0,
1) and mergesort(1, 3), which do not perform
any recursive calls because segments (0, 1)
and (1, 3) are sorted.
Hence, total mergesort calls are 3.
Input : n = 4
k = 1
Output : a[] = {1, 2, 3, 4}
Explanation:
Here, a[] = {1, 2, 3, 4} then there will be
1 mergesort call — mergesort(0, 4), which
will check that the array is sorted and then
end.
If we have value of k even, then there is no solution, since the number of calls is always odd
(one call in the beginning, and each call makes either 0 or 2 recursive calls).
703
Chapter 97. Find array with k number of merge sort calls
If k is odd, let’s try to start with a sorted permutation and try to “unsort” it. Let’s make
a function unsort(l, r) that will do it. When we “unsort” a segment, we can either keep it
sorted (if we already made enough calls), or make it non-sorted and then call unsort(l, mid)
and unsort(mid, r), if we need more calls. When we make a segment non-sorted, it’s better
to keep its both halves sorted; an easy way to handle this is to swap two middle element.
It’s easy to see that the number of unsort calls is equal to the number of mergesort calls to
sort the resulting permutation, so we can use this approach to try getting exactly k calls.
Below is the code for the above problem.
CPP
704
Chapter 97. Find array with k number of merge sort calls
for (int i = 0; i < n; ++i)
cout << a[i] << ' ';
}
// Driver code
int main()
{
int n = 10, k = 17;
arrayWithKCalls(n, k);
return 0;
}
Java
705
Chapter 97. Find array with k number of merge sort calls
a[0] = 1;
for (int i = 1; i < n; i++)
a[i] = i + 1;
k--;
// calling unsort function
unsort(0, n, a, k);
for (int i = 0; i < n; ++i)
System.out.print(a[i] + " ");
}
// Driver code
public static void main(String[] args)
{
int n = 10, k = 17;
arrayWithKCalls(n, k);
}
}
// This code is contributed by Anant Agarwal.
Python3
706
Chapter 97. Find array with k number of merge sort calls
def arrayWithKCalls(n,k):
if (k % 2 == 0):
print("NO SOLUTION")
return
# Create an array with values
# in [1, n]
a = [0 for i in range(n + 2)]
a[0] = 1
for i in range(1, n):
a[i] = i + 1
k-=1
# calling unsort function
unsort(0, n, a, k)
for i in range(n):
print(a[i] ," ",end="")
# Driver code
n = 10
k = 17
arrayWithKCalls(n, k)
# This code is contributed
# by Anant Agarwal.
C#
707
Chapter 97. Find array with k number of merge sort calls
int mid = (l + r) / 2;
int temp = a[mid - 1];
a[mid - 1] = a[mid];
a[mid] = temp;
unsort(l, mid, a, k);
unsort(mid, r, a, k);
}
static void arrayWithKCalls(int n, int k)
{
if (k % 2 == 0)
{
Console.WriteLine("NO SOLUTION");
return;
}
// Create an array with
// values in [1, n]
int []a = new int[n + 1];
a[0] = 1;
for (int i = 1; i < n; i++)
a[i] = i + 1;
k--;
// calling unsort function
unsort(0, n, a, k);
for (int i = 0; i < n; ++i)
Console.Write(a[i] + " ");
}
// Driver code
public static void Main()
{
int n = 10, k = 17;
arrayWithKCalls(n, k);
}
}
// This code is contributed by vt_m.
Output:
708
Chapter 97. Find array with k number of merge sort calls
3 1 4 6 2 8 5 9 7 10
Improved By : vt_m
Source
https://www.geeksforgeeks.org/find-array-k-number-merge-sort-calls/
709
Chapter 98
Method 1: Using three nested loops. Check if an element of 1st row is present in all the
subsequent rows. Time Complexity of O(n3 ). Extra space could be required to handle the
duplicate elements.
Method 2: Sort all the rows of the matrix individually in increasing order. Then apply a
modified approach of the problem of finding common elements in 3 sorted arrays. Below an
implementation for the same is given.
C++
710
Chapter 98. Find distinct elements common to all rows of a matrix
711
Chapter 98. Find distinct elements common to all rows of a matrix
Java
712
Chapter 98. Find distinct elements common to all rows of a matrix
713
Chapter 98. Find distinct elements common to all rows of a matrix
// if all elements of the row have
// been traversed
if (curr_index[i] == n)
{
f = 1;
break;
}
}
// if the 'value' is common to all the rows
if (present)
System.out.print(value+" ");
// if any row have been completely traversed
// then no more common elements can be found
if (f == 1)
break;
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int mat[][] = { {12, 1, 14, 3, 16},
{14, 2, 1, 3, 35},
{14, 1, 14, 3, 11},
{14, 25, 3, 2, 1},
{1, 18, 3, 21, 14}
};
int n = 5;
findAndPrintCommonElements(mat, n);
}
}
// This code is contributed by Arnav Kr. Mandal.
Output:
1 3 14
Time Complexity: O(n2 log n), each row of size n requires O(nlogn) for sorting and there
are total n rows.
Auxiliary Space : O(n) to store current column indexes for each row.
714
Chapter 98. Find distinct elements common to all rows of a matrix
3. Map each element of the current row into a temporary hash table. Let it be temp.
4. Iterate through the elements of hash and check that the elements in hash are present
in temp. If not present then delete those elements from hash.
5. When all the rows are being processed in this manner, then the elements left in hash
are the required common elements.
715
Chapter 98. Find distinct elements common to all rows of a matrix
// if size of 'us' becomes 0,
// then there are no common elements
if (us.size() == 0)
break;
}
// print the common elements
unordered_set<int>:: iterator itr;
for (itr=us.begin(); itr!=us.end(); itr++)
cout << *itr << " ";
}
// Driver program to test above
int main()
{
int mat[][MAX] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
int n = 4;
findAndPrintCommonElements(mat, n);
return 0;
}
Output:
3 2
Source
https://www.geeksforgeeks.org/find-distinct-elements-common-rows-matrix/
716
Chapter 99
A naive approach is to take an element and compare with all other elements and if it is
greater then increment the count and then check if count is greater than n/2 elements then
print.
An efficient method is to sort the array in ascending order and then print last ceil(n/2)
elements from sorted array.
Below is C++ implementation of this sorting based approach.
C/C++
717
Chapter 99. Find elements larger than half of the elements in an array
Java
718
Chapter 99. Find elements larger than half of the elements in an array
Python
C#
719
Chapter 99. Find elements larger than half of the elements in an array
PHP
<?php
// PHP program to find elements
// that are larger than half of
// the elements in array
// Prints elements larger
// than n/2 element
function findLarger($arr, $n)
{
// Sort the array in
// ascending order
sort($arr);
// Print last ceil(n/2) elements
for ($i = $n - 1; $i >= $n / 2; $i--)
echo $arr[$i] , " ";
}
// Driver Code
$arr = array(1, 3, 6, 1, 0, 9);
$n = count($arr);
findLarger($arr, $n);
// This code is contributed by anuj_67.
?>
Output :
9 6 3
720
Chapter 99. Find elements larger than half of the elements in an array
Source
https://www.geeksforgeeks.org/find-elements-larger-half-elements-array/
721
Chapter 100
Input : [2 3 4]
k = 3
Output : [1 5 6]
Input : [-2 -3 4]
k = 2
Output : [1 2]
722
Chapter 100. Find first k natural numbers missing in given array
Java
723
Chapter 100. Find first k natural numbers missing in given array
import java.util.Arrays;
class GFG {
// Prints first k natural numbers in
// arr[0..n-1]
static void printKMissing(int[] arr, int n, int k)
{
Arrays.sort(arr);
// Find first positive number
int i = 0;
while (i < n && arr[i] <= 0)
i++;
// Now find missing numbers
// between array elements
int count = 0, curr = 1;
while (count < k && i < n) {
if (arr[i] != curr) {
System.out.print(curr + " ");
count++;
}
else
i++;
curr++;
}
// Find missing numbers after
// maximum.
while (count < k) {
System.out.print(curr + " ");
curr++;
count++;
}
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 2, 3, 4 };
int n = arr.length;
int k = 3;
printKMissing(arr, n, k);
}
}
/* This code is contributed by Mr. Somesh Awasthi */
C#
724
Chapter 100. Find first k natural numbers missing in given array
725
Chapter 100. Find first k natural numbers missing in given array
}
// This code is contributed by Nitin Mittal
PHP
<?php
// PHP program to find missing k numbers
// in an array.
// Prints first k natural numbers in
// arr[0..n-1]
function printKMissing($arr, $n, $k)
{
sort($arr); sort($arr , $n);
// Find first positive number
$i = 0;
while ($i < $n && $arr[$i] <= 0)
$i++;
// Now find missing numbers
// between array elements
$count = 0; $curr = 1;
while ($count < $k && $i < $n) {
if ($arr[$i] != $curr) {
echo $curr , " ";
$count++;
}
else
$i++;
$curr++;
}
// Find missing numbers after
// maximum.
while ($count < $k) {
echo $curr , " ";
$curr++;
$count++;
}
}
// Driver code
$arr =array ( 2, 3, 4 );
$n = sizeof($arr);
$k = 3;
726
Chapter 100. Find first k natural numbers missing in given array
Output:
1 5 6
Source
https://www.geeksforgeeks.org/find-first-k-natural-numbers-missing-given-array/
727
Chapter 101
Find four elements that sum to a given value Set 2 ( O(n^2Logn) Solution) - GeeksforGeeks
Given an array of integers, find any one combination of four elements in the array whose
sum is equal to a given value X.
For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and X = 23, then your function
should print “3 5 7 8” (3 + 5 + 7 + 8 = 23).
We have discussed a O(n^3) algorithm in the previous post on this topic. The problem can
be solved in O(n^2Logn) time with the help of auxiliary space.
Thanks to itsnimish for suggesting this method. Following is the detailed process.
Let the input array be A[].
1) Create an auxiliary array aux[] and store sum of all possible pairs in aux[]. The size of
aux[] will be n*(n-1)/2 where n is the size of A[].
2) Sort the auxiliary array aux[].
3) Now the problem reduces to find two elements in aux[] with sum equal to X. We can use
method 1 ofthis postto find the two elements efficiently. There is following important point
to note though. An element of aux[] represents a pair from A[]. While picking two elements
from aux[], we must check whether the two elements have an element of A[] in common. For
example, if first element sum of A[1] and A[2], and second element is sum of A[2] and A[4],
then these two elements of aux[] don’t represent four distinct elements of input array A[].
Following is C implementation of this method.
#include <stdio.h>
#include <stdlib.h>
728
Chapter 101. Find four elements that sum to a given value Set 2 ( O(n^2Logn) Solution)
// The following structure is needed to store pair sums in aux[]
struct pairSum
{
int first; // index (int A[]) of first element in pair
int sec; // index of second element in pair
int sum; // sum of the pair
};
// Following function is needed for library function qsort()
int compare (const void *a, const void * b)
{
return ( (*(pairSum *)a).sum - (*(pairSum*)b).sum );
}
// Function to check if two given pairs have any common element or not
bool noCommon(struct pairSum a, struct pairSum b)
{
if (a.first == b.first || a.first == b.sec ||
a.sec == b.first || a.sec == b.sec)
return false;
return true;
}
// The function finds four elements with given sum X
void findFourElements (int arr[], int n, int X)
{
int i, j;
// Create an auxiliary array to store all pair sums
int size = (n*(n-1))/2;
struct pairSum aux[size];
/* Generate all possible pairs from A[] and store sums
of all possible pairs in aux[] */
int k = 0;
for (i = 0; i < n-1; i++)
{
for (j = i+1; j < n; j++)
{
aux[k].sum = arr[i] + arr[j];
aux[k].first = i;
aux[k].sec = j;
k++;
}
}
729
Chapter 101. Find four elements that sum to a given value Set 2 ( O(n^2Logn) Solution)
// Sort the aux[] array using library function for sorting
qsort (aux, size, sizeof(aux[0]), compare);
// Now start two index variables from two corners of array
// and move them toward each other.
i = 0;
j = size-1;
while (i < size && j >=0 )
{
if ((aux[i].sum + aux[j].sum == X) && noCommon(aux[i], aux[j]))
{
printf ("%d, %d, %d, %d\n", arr[aux[i].first], arr[aux[i].sec],
arr[aux[j].first], arr[aux[j].sec]);
return;
}
else if (aux[i].sum + aux[j].sum < X)
i++;
else
j--;
}
}
// Driver program to test above function
int main()
{
int arr[] = {10, 20, 30, 40, 1, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int X = 91;
findFourElements (arr, n, X);
return 0;
}
Output:
20, 1, 30, 40
Please note that the above code prints only one quadruple. If we remove the return statement
and add statements “i++; j–;”, then it prints same quadruple five times. The code can
modified to print all quadruples only once. It has been kept this way to keep it simple.
Time complexity: The step 1 takes O(n^2) time. The second step is sorting an array of
size O(n^2). Sorting can be done in O(n^2Logn) time using merge sort or heap sort or
any other O(nLogn) algorithm. The third step takes O(n^2) time. So overall complexity is
O(n^2Logn).
Auxiliary Space: O(n^2). The big size of auxiliary array can be a concern in this method.
730
Chapter 101. Find four elements that sum to a given value Set 2 ( O(n^2Logn) Solution)
2. Traverse through all pairs again and search for X – (current pair sum) in the hash
table.
3. If a pair is found with the required sum, then make sure that all elements are distinct
array elements and an element is not considered more than once.
731
Chapter 101. Find four elements that sum to a given value Set 2 ( O(n^2Logn) Solution)
// Driver program to test above function
int main()
{
int arr[] = {10, 20, 30, 40, 1, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int X = 91;
findFourElements(arr, n, X);
return 0;
}
Source
https://www.geeksforgeeks.org/find-four-elements-that-sum-to-a-given-value-set-2/
732
Chapter 102
Find if k bookings possible with given arrival and departure times - GeeksforGeeks
A hotel manager has to process N advance bookings of rooms for the next season. His hotel
has K rooms. Bookings contain an arrival date and a departure date. He wants to find out
whether there are enough rooms in the hotel to satisfy the demand.
The idea is to sort the arrays and keep track of overlaps.
Examples:
Input : Arrivals : [1 3 5]
Departures : [2 6 8]
K : 1
Output : False
Hotel manager needs at least two
rooms as the second and third
intervals overlap.
The idea is store arrival and departure times in an auxiliary array with an additional marker
to indicate whether time is arrival or departure. Now sort the array. Process the sorted
array, for every arrival increment active bookings. And for every departure, decrement.
Keep track of maximum active bookings. If count of active bookings at any moment is more
than k, then return false. Else return return true.
Below is the c++ code for above approach.
#include <bits/stdc++.h>
733
Chapter 102. Find if k bookings possible with given arrival and departure times
734
Chapter 102. Find if k bookings possible with given arrival and departure times
Output:
No
Source
https://www.geeksforgeeks.org/find-k-bookings-possible-given-arrival-departure-times/
735
Chapter 103
Method 1: We search for the maximum element k times in the given array. Each time we
find one maximum element, we print it and repalce it with minus infinite (INT_MIN in C)
in the array. The time complexity of this method is O(n*k).
Method 2: In this method, we store the original array in a new array and will sort the
new array in descending order. After sorting, we iterate the original array from 0 to n and
print all those elements that appear in first k elements of new array. For searching, we can
do Binary Search.
C++
736
Chapter 103. Find k maximum elements of array in original order
Java
737
Chapter 103. Find k maximum elements of array in original order
// Function to print m Maximum elements
public static void printMax(int arr[], int k, int n)
{
// Array to store the copy
// of the original array
Integer[] brr = new Integer[n];
for (int i = 0; i < n; i++)
brr[i] = arr[i];
// Sorting the array in
// descending order
Arrays.sort(brr, Collections.reverseOrder());
// Traversing through original array and
// printing all those elements that are
// in first k of sorted array.
// Please refer https://goo.gl/uj5RCD
// for details of Arrays.binarySearch()
for (int i = 0; i < n; ++i)
if (Arrays.binarySearch(brr, arr[i],
Collections.reverseOrder()) >= 0
&& Arrays.binarySearch(brr, arr[i],
Collections.reverseOrder()) < k)
System.out.print(arr[i]+ " ");
}
// Driver code
public static void main(String args[])
{
int arr[] = { 50, 8, 45, 12, 25, 40, 84 };
int n = arr.length;
int k = 3;
printMax(arr, k, n);
}
}
// This code is contributed by Swetank Modi
Output :
50 45 84
738
Chapter 103. Find k maximum elements of array in original order
Source
https://www.geeksforgeeks.org/find-k-maximum-elements-array-original-order/
739
Chapter 104
The idea is to first Prerequisite : Merge Overlapping Intervals and keep all intervals sorted
740
Chapter 104. Find k-th smallest element in given n ranges
in ascending order of start time. After merging in an array merged[], we use linear search
to find kth smallest element. Below is the implementation of the above approach :
741
Chapter 104. Find k-th smallest element in given n ranges
{
// Sorting intervals according to start
// time
sort(arr, arr + n, comp);
// Merging all intervals into merged
merged.push_back(arr[0]);
for (int i = 1; i < n; i++)
{
// To check if starting point of next
// range is lying between the previous
// range and ending point of next range
// is greater than the Ending point
// of previous range then update ending
// point of previous range by ending
// point of next range.
Interval prev = merged.back();
Interval curr = arr[i];
if ((curr.s >= prev.s &&
curr.s <= prev.e) &&
(curr.e > prev.e))
merged.back().e = curr.e;
else
{
// If starting point of next range
// is greater than the ending point
// of previous range then store next range
// in merged[].
if (curr.s > prev.e)
merged.push_back(curr);
}
}
}
// Driver\'s Function
int main()
{
Interval arr[] = {{2, 6}, {4, 7}};
int n = sizeof(arr)/sizeof(arr[0]);
int query[] = {5, 8};
int q = sizeof(query)/sizeof(query[0]);
// Merge all intervals into merged[]
vector<Interval>merged;
mergeIntervals(merged, arr, n);
742
Chapter 104. Find k-th smallest element in given n ranges
Output:
6
-1
Source
https://www.geeksforgeeks.org/find-k-th-smallest-element-in-given-n-ranges/
743
Chapter 105
Find maximum height pyramid from the given array of objects - GeeksforGeeks
Given n objects, with each object has width wi . We need to arrange them in a pyramidal
way such that :
744
Chapter 105. Find maximum height pyramid from the given array of objects
The task is to find the maximum height that can be achieved from given objects.
Examples :
The idea is to use greedy approach by placing the object with the lowest width at the top,
the next object at the level right below and so on.
To find the maximum number of levels, sort the given array and try to form pyramid from
top to bottom. Find the smallest element of array i.e first element of array after sorting,
place it on the top. Then try to build levels below it with greater number of objects and
greater width.
Below is the implementation of this approach:
C++
745
Chapter 105. Find maximum height pyramid from the given array of objects
int curr_count = 0;
// Width of current level.
int curr_width = 0;
for (int i=1; i<n; i++)
{
// Picking the object. So increase current
// width and number of object.
curr_width += boxes[i];
curr_count += 1;
// If current width and number of object
// are greater than previous.
if (curr_width > prev_width &&
curr_count > prev_count)
{
// Update previous width, number of
// object on previous level.
prev_width = curr_width;
prev_count = curr_count;
// Reset width of current level, number
// of object on current level.
curr_count = 0;
curr_width = 0;
// Increment number of level.
ans++;
}
}
return ans;
}
// Driver Program
int main()
{
int boxes[] = {10, 20, 30, 50, 60, 70};
int n = sizeof(boxes)/sizeof(boxes[0]);
cout << maxLevel(boxes, n) << endl;
return 0;
}
Java
746
Chapter 105. Find maximum height pyramid from the given array of objects
import java.util.Arrays;
class GFG {
// Returns maximum number of pyramidcal
// levels n boxes of given widths.
static int maxLevel(int []boxes, int n)
{
// Sort objects in increasing order
// of widths
Arrays.sort(boxes);
int ans = 1; // Initialize result
// Total width of previous level
// and total number of objects in
// previous level
int prev_width = boxes[0];
int prev_count = 1;
// Number of object in current
// level.
int curr_count = 0;
// Width of current level.
int curr_width = 0;
for (int i = 1; i < n; i++)
{
// Picking the object. So
// increase current width
// and number of object.
curr_width += boxes[i];
curr_count += 1;
// If current width and
// number of object
// are greater than previous.
if (curr_width > prev_width &&
curr_count > prev_count)
{
// Update previous width,
// number of object on
// previous level.
prev_width = curr_width;
prev_count = curr_count;
747
Chapter 105. Find maximum height pyramid from the given array of objects
Python 3
748
Chapter 105. Find maximum height pyramid from the given array of objects
# Number of object in
# current level.
curr_count = 0
# Width of current level.
curr_width = 0
for i in range(1, n):
# Picking the object. So
# increase current width
# and number of object.
curr_width += boxes[i]
curr_count += 1
# If current width and
# number of object are
# greater than previous.
if (curr_width > prev_width and
curr_count > prev_count):
# Update previous width,
# number of object on
# previous level.
prev_width = curr_width
prev_count = curr_count
# Reset width of current
# level, number of object
# on current level.
curr_count = 0
curr_width = 0
# Increment number of level.
ans += 1
return ans
# Driver Code
if __name__ == "__main__":
boxes= [10, 20, 30, 50, 60, 70]
n = len(boxes)
print(maxLevel(boxes, n))
# This code is contributed
# by ChitraNayal
C#
749
Chapter 105. Find maximum height pyramid from the given array of objects
750
Chapter 105. Find maximum height pyramid from the given array of objects
// Reset width of current
// level, number of object
// on current level.
curr_count = 0;
curr_width = 0;
// Increment number of
// level.
ans++;
}
}
return ans;
}
// Driver Program
static public void Main ()
{
int []boxes = {10, 20, 30, 50, 60, 70};
int n = boxes.Length;
Console.WriteLine(maxLevel(boxes, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find maximum
// height pyramid from the
// given object width.
// Returns maximum number of
// pyramidcal levels n boxes
// of given widths.
function maxLevel($boxes, $n)
{
// Sort objects in increasing
// order of widths
sort($boxes);
// Initialize result
$ans = 1;
// Total width of previous
// level and total number
751
Chapter 105. Find maximum height pyramid from the given array of objects
752
Chapter 105. Find maximum height pyramid from the given array of objects
?>
Output :
Source
https://www.geeksforgeeks.org/find-maximum-height-pyramid-from-the-given-array-of-objects/
753
Chapter 106
Input:
(1, 512, 1, R)
(2, 432, 2, W)
(3, 512, 3, R)
(4, 932, 4, R)
(5, 512, 5, W)
(6, 932, 6, R)
(7, 835, 7, R)
(8, 432, 8, R)
754
Chapter 106. Find memory conflicts among multiple threads
Output:
Thread 1 & 3 conflict with thread 5
All other operations are safe.
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to sort all threads by memory block and if memory block is same, then by time.
Once we have all threads sorted, we can traverse all threads one by one. For every thread
being traversed, we simply need to check previous adjacent threads of same block as threads
are sorted by time.
Below is C++ implementation of this idea.
755
Chapter 106. Find memory conflicts among multiple threads
{
/* As threads with same block are sorted in increasing order
of access time. So we check possibility conflict from last
thread to all previous threads which access the same block
of memory such that the current thread access under the
arr[i-1].time + 5.. and if any of them does read operation
than conflict occurs. at any point memblock becomes different
or current thread moves out of vulnerable time of latest
previous processed thread, the loop breaks.
*/
if (arr[i].time <= arr[i-1].time+5)
{
int j = i-1; /* start with previous thread */
// Find all previous conflicting threads
while (arr[i].memblck == arr[j].memblck &&
arr[i].time <= arr[j].time+5 &&
j >= 0)
{
if (arr[i].access == 'W' || arr[j].access == 'W')
{
cout << "threads " << arr[j].id << " and "
<< arr[i].id << " conflict.\n";
}
j--;
}
}
}
}
cout << "All other operations are same\n";
}
// Driver program to test above function
int main()
{
Thread arr[] = { {1, 512, 1, 'R'}, {2, 432, 2, 'W'},
{3, 512, 3, 'R'}, {4, 932, 4, 'R'},
{5, 512, 5, 'W'}, {6, 932, 6, 'R'},
{7, 835, 7, 'R'}, {8, 432, 8, 'R'}
};
int n = sizeof(arr)/sizeof(arr[0]);
printConflicts(arr, n);
return 0;
}
756
Chapter 106. Find memory conflicts among multiple threads
Output:
Time complexity: The above solution uses sorting to sort threads. Sorting can be done
in O(nLogn) time. Then it prints all conflicts. Printing all conflicts takes O(n + m) time
where m is number of conflicts. So overall time complexity is O(nLogn + m).
This article is contributed by Gaurav Ahirwar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/find-memory-conflicts-among-multiple-threads/
757
Chapter 107
758
Chapter 107. Find minimum difference between any two elements
Java
759
Chapter 107. Find minimum difference between any two elements
// Driver method to test the above function
public static void main(String[] args)
{
int arr[] = new int[]{1, 5, 3, 19, 18, 25};
System.out.println("Minimum difference is "+
findMinDiff(arr, arr.length));
}
}
Python
C#
760
Chapter 107. Find minimum difference between any two elements
PHP
<?php
// PHP implementation of simple
// method to find minimum
// difference between any pair
// Returns minimum difference
// between any pair
function findMinDiff($arr, $n)
{
// Initialize difference
// as infinite
$diff = PHP_INT_MAX;
// Find the min diff by comparing
// difference of all possible
// pairs in given array
for ($i = 0; $i < $n - 1; $i++)
for ($j = $i + 1; $j < $n; $j++)
761
Chapter 107. Find minimum difference between any two elements
Output :
Minimum difference is 1
762
Chapter 107. Find minimum difference between any two elements
Java
763
Chapter 107. Find minimum difference between any two elements
Python
C#
764
Chapter 107. Find minimum difference between any two elements
PHP
<?php
// PHP program to find minimum
// difference between any pair
// in an unsorted array
// Returns minimum difference
// between any pair
function findMinDiff($arr, $n)
{
// Sort array in
765
Chapter 107. Find minimum difference between any two elements
// non-decreasing order
sort($arr);
// Initialize difference
// as infinite
$diff = PHP_INT_MAX;
// Find the min diff by
// comparing adjacent
// pairs in sorted array
for ($i = 0; $i < $n - 1; $i++)
if ($arr[$i + 1] - $arr[$i] < $diff)
$diff = $arr[$i + 1] - $arr[$i];
// Return min diff
return $diff;
}
// Driver code
$arr = array(1, 5, 3, 19, 18, 25);
$n = sizeof($arr);
echo "Minimum difference is " ,
findMinDiff($arr, $n);
// This code is contributed ajit
?>
Output :
Minimum difference is 1
This article is contributed by Harshit Agrawal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : nitin mittal, vt_m, jit_t
Source
https://www.geeksforgeeks.org/find-minimum-difference-pair/
766
Chapter 108
1. Use Sorting : Sort the array, then do binary search for ‘low’. Once location of low is
find, start traversing array from that location and keep printing all missing numbers.
C++
767
Chapter 108. Find missing elements of a range
768
Chapter 108. Find missing elements of a range
Java
769
Chapter 108. Find missing elements of a range
}
// Utility function to find ceil index of given element
static int ceilindex(int ar[], int val, int low, int high)
{
if (val < ar[0])
return 0;
if (val > ar[ar.length - 1])
return ar.length;
int mid = (low + high) / 2;
if (ar[mid] == val)
return mid;
if (ar[mid] < val)
{
if (mid + 1 < high && ar[mid + 1] >= val)
return mid + 1;
return ceilindex(ar, val, mid + 1, high);
}
else
{
if (mid - 1 >= low && ar[mid - 1] < val)
return mid;
return ceilindex(ar, val, low, mid - 1);
}
}
// Driver program to test above function
public static void main(String[] args)
{
int arr[] = { 1, 3, 5, 4 };
int low = 1, high = 10;
printMissing(arr, low, high);
}
}
// This code is contributed by Rishabh Mahrsee
Output:
2 6 7 8 9 10
2. Use Hashing : Create a hash table and insert all array items into the hash table.
Once all items are in hash table, traverse through the range and print all missing
elements.
C++
770
Chapter 108. Find missing elements of a range
Java
771
Chapter 108. Find missing elements of a range
Output:
2 6 7 8 9 10
Source
https://www.geeksforgeeks.org/find-missing-elements-of-a-range/
772
Chapter 109
Find number of pairs (x, y) in an array such that x^y > y^x - GeeksforGeeks
Given two arrays X[] and Y[] of positive integers, find number of pairs such that x^y >
y^x where x is an element from X[] and y is an element from Y[].
Examples:
The brute force solution is to consider each element of X[] and Y[], and check whether
the given condition satisfies or not. Time Complexity of this solution is O(m*n) where m
and n are sizes of given arrays.
Following is C++ code based on brute force solution.
773
Chapter 109. Find number of pairs (x, y) in an array such that x^y > y^x
Efficient Solution:
The problem can be solved in O(nLogn + mLogn) time. The trick here is, if y > x then
x^y > y^x with some exceptions. Following are simple steps based on this trick.
1) Sort array Y[].
2) For every x in X[], find the index idx of smallest number greater than x (also called ceil of
x) in Y[] using binary search or we can use the inbuilt function upper_bound() in algorithm
library.
3) All the numbers after idx satisfy the relation so just add (n-idx) to the count.
Base Cases and Exceptions:
Following are exceptions for x from X[] and y from Y[]
If x = 0, then the count of pairs for this x is 0.
If x = 1, then the count of pairs for this x is equal to count of 0s in Y[].
The following cases must be handled separately as they don’t follow the general rule that x
smaller than y means x^y is greater than y^x.
a) x = 2, y = 3 or 4
b) x = 3, y = 2
Note that the case where x = 4 and y = 2 is not there
Following diagram shows all exceptions in tabular form. The value 1 indicates that the
corresponding (x, y) form a valid pair.
774
Chapter 109. Find number of pairs (x, y) in an array such that x^y > y^x
#include<iostream>
#include<algorithm>
using namespace std;
// This function return count of pairs with x as one element
// of the pair. It mainly looks for all values in Y[] where
// x ^ Y[i] > Y[i] ^ x
int count(int x, int Y[], int n, int NoOfY[])
{
// If x is 0, then there cannot be any value in Y such that
// x^Y[i] > Y[i]^x
if (x == 0) return 0;
// If x is 1, then the number of pais is equal to number of
// zeroes in Y[]
if (x == 1) return NoOfY[0];
// Find number of elements in Y[] with values greater than x
// upper_bound() gets address of first greater element in Y[0..n-1]
int* idx = upper_bound(Y, Y + n, x);
int ans = (Y + n) - idx;
// If we have reached here, then x must be greater than 1,
// increase number of pairs for y=0 and y=1
ans += (NoOfY[0] + NoOfY[1]);
// Decrease number of pairs for x=2 and (y=4 or y=3)
if (x == 2) ans -= (NoOfY[3] + NoOfY[4]);
// Increase number of pairs for x=3 and y=2
if (x == 3) ans += NoOfY[2];
return ans;
}
// The main function that returns count of pairs (x, y) such that
// x belongs to X[], y belongs to Y[] and x^y > y^x
int countPairs(int X[], int Y[], int m, int n)
{
// To store counts of 0, 1, 2, 3 and 4 in array Y
int NoOfY[5] = {0};
for (int i = 0; i < n; i++)
if (Y[i] < 5)
NoOfY[Y[i]]++;
// Sort Y[] so that we can do binary search in it
sort(Y, Y + n);
775
Chapter 109. Find number of pairs (x, y) in an array such that x^y > y^x
int total_pairs = 0; // Initialize result
// Take every element of X and count pairs with it
for (int i=0; i<m; i++)
total_pairs += count(X[i], Y, n, NoOfY);
return total_pairs;
}
// Driver program to test above functions
int main()
{
int X[] = {2, 1, 6};
int Y[] = {1, 5};
int m = sizeof(X)/sizeof(X[0]);
int n = sizeof(Y)/sizeof(Y[0]);
cout << "Total pairs = " << countPairs(X, Y, m, n);
return 0;
}
Java
776
Chapter 109. Find number of pairs (x, y) in an array such that x^y > y^x
777
Chapter 109. Find number of pairs (x, y) in an array such that x^y > y^x
C#
778
Chapter 109. Find number of pairs (x, y) in an array such that x^y > y^x
779
Chapter 109. Find number of pairs (x, y) in an array such that x^y > y^x
Console.Write("Total pairs = " +
countPairs(X, Y, X.Length, Y.Length));
}
}
// This code is contributed by Sam007
Output:
Total pairs = 3
Time Complexity : Let m and n be the sizes of arrays X[] and Y[] respectively. The sort
step takes O(nLogn) time. Then every element of X[] is searched in Y[] using binary search.
This step takes O(mLogn) time. Overall time complexity is O(nLogn + mLogn).
This article is contributed by Shubham Mittal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/find-number-pairs-xy-yx/
780
Chapter 110
Given an array of size N. Find the number of pairs (i, j) such that XOR =
0, and 1 <= i < j <= N.
Examples :
to the answer.
781
Chapter 110. Find number of pairs in an array such that their XOR is 0
782
Chapter 110. Find number of pairs in an array such that their XOR is 0
Java
783
Chapter 110. Find number of pairs in an array such that their XOR is 0
Python3
784
Chapter 110. Find number of pairs in an array such that their XOR is 0
C#
785
Chapter 110. Find number of pairs in an array such that their XOR is 0
PHP
<?php
// PHP program to find number
// of pairs in an array such
// that their XOR is 0
// Function to calculate
// the count
function calculate($a, $n)
{
// Sorting the list using
// built in function
sort($a);
$count = 1;
$answer = 0;
// Traversing through the
// elements
for ($i = 1; $i < $n; $i++)
{
786
Chapter 110. Find number of pairs in an array such that their XOR is 0
Output :
787
Chapter 110. Find number of pairs in an array such that their XOR is 0
Python 3
788
Chapter 110. Find number of pairs in an array such that their XOR is 0
PHP
Output :
789
Chapter 110. Find number of pairs in an array such that their XOR is 0
Source
https://www.geeksforgeeks.org/find-number-pairs-array-xor-0/
790
Chapter 111
A naive approach is to pick an element and then check for each pair product if equal to
that number and update the max if the number is maximum,repeat until whole array gets
traversed takes O(n^3) time.
C++
791
Chapter 111. Find pair with greatest product in array
Java
792
Chapter 111. Find pair with greatest product in array
C#
PHP
<?php
// PHP program to find a pair
793
Chapter 111. Find pair with greatest product in array
Output :
30
1. Create an empty hash table and store all array elements in it.
2. Sort the array in ascending order.
3. Pick elements one by one from end of the array.
4. And check if there exists a pair whose product is equal to that number. In this
efficiency can be achieved. The idea is to reach till sqrt of that number. If we don’t
get the pair till sqrt that means no such pair exists. We use hash table to make sure
that we can find other element of pair in O(1) time.
5. Repeat steps 2 to 3 until we get the element or whole array gets traversed.
794
Chapter 111. Find pair with greatest product in array
795
Chapter 111. Find pair with greatest product in array
return 0;
}
Output :
30
Improved By : vt_m
Source
https://www.geeksforgeeks.org/find-pair-with-greatest-product-in-array/
796
Chapter 112
Find shortest unique prefix for every word in a given list Set 2 (Using Sorting) - Geeks-
forGeeks
Given an array of words, find all shortest unique prefixes to represent each word in the given
array. Assume that no word is a prefix of another. Output the shortest unique prefixes in
sorted order.
797
Chapter 112. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)
Now, the shortest unique prefix for “dove” is the one with greater length between “dov” and
“do”. So, it is “dov”.
The shortest unique prefix for first and last string can be found by comparing them with
only 1 most similar neighbor on right and left, respectively.
We can sort the array of strings and keep on doing this for every string of the array.
798
Chapter 112. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)
j++;
else
break;
}
String new_prefix = a[i].substring(0, j+1);
/* compare the new prefix with previous prefix */
if (temp_prefix.length() > new_prefix.length() )
res[ind++] = temp_prefix;
else
res[ind++] = new_prefix;
/* store the prefix of a[i+1] unique from its
left neighbour */
temp_prefix = a[i+1].substring(0, j+1);
}
/* compute the unique prefix for the last string
in sorted array */
j = 0;
String sec_last = a[size-2] ;
String last = a[size-1];
while (j < Math.min( sec_last.length()-1, last.length()-1))
{
if (sec_last.charAt(j) == last.charAt(j))
j++;
else
break;
}
res[ind] = last.substring(0, j+1);
return res;
}
/* Driver Function to test other function */
public static void main(String[] args)
{
GFG gfg = new GFG();
String[] input = {"zebra", "dog", "duck", "dove"};
String[] output = gfg.uniquePrefix(input);
System.out.println( "The shortest unique prefixes" +
" in sorted order are :");
799
Chapter 112. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)
Output:
If we want to output the prefixes as the order of strings in the input array, we
can store the string and its corresponding index in the hashmap. While adding the prefix
to result array, we can get the index of the corresponding string from hashmap and add the
prefix to that index.
800
Chapter 112. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)
j++;
else
break;
}
/* get the index of a[0] from HashMap */
res[ hm.get(a[0]) ] = a[0].substring(0, j+1);
/* Store the unique prefix of a[1] from its
left neighbor */
String temp_prefix= a[1].substring(0, j+1);
for (int i = 1; i < size-1; i++)
{
/* compute prefix of a[i] unique from its right neighbor */
j = 0;
while (j < Math.min(a[i].length()-1, a[i+1].length()-1))
{
if (a[i].charAt(j) == a[i+1].charAt(j) )
j++;
else
break;
}
String new_prefix = a[i].substring(0, j+1);
/* compare the new prefix with previous prefix */
if (temp_prefix.length() > new_prefix.length() )
res[ hm.get(a[i]) ] = temp_prefix;
else
res[ hm.get(a[i]) ] = new_prefix;
/* store the prefix of a[i+1] unique from its
left neighbour */
temp_prefix = a[i+1].substring(0, j+1);
}
/* compute the unique prefix for the last string
in sorted array */
String sec_last = a[size-2];
String last = a[size-1];
j = 0;
while (j < Math.min( sec_last.length()-1, last.length()-1))
{
if (sec_last.charAt(j) == last.charAt(j) )
j++;
801
Chapter 112. Find shortest unique prefix for every word in a given list Set 2 (Using
Sorting)
else
break;
}
res[ hm.get(last) ] = last.substring(0, j+1);
return res;
}
/* Driver Function to test other function */
public static void main(String[] args)
{
GFG gfg = new GFG();
String[] input = {"zebra", "dog", "duck", "dove"};
String[] output = gfg.uniquePrefix(input);
System.out.println( "The shortest unique prefixes are :");
for (int i=0; i < output.length; i++)
System.out.print( output[i] + " ");
}
}
Output:
For a more efficient solution, we can use Trie as discussed in this post.
Source
https://www.geeksforgeeks.org/find-shortest-unique-prefix-every-word-given-list-set-2-using-sorting/
802
Chapter 113
A Simple Solution is to use two nested loops. The outer loop picks an element one by one
starting from the leftmost element. The inner loop checks if the element is present on left
side of it. If present, then ignores the element.
Time Complexity : O(n2 )
Auxiliary Space : O(1)
A Better Solution of this problem is that using sorting technique we firstly sort all elements
of array in ascending order and and find one by one distinct elements in array.
803
Chapter 113. Find sum of non-repeating (distinct) elements in an array
// Find the sum of all non-repeated elements
// in an array
int findSum(int arr[], int n)
{
// sort all elements of array
sort(arr, arr + n);
int sum = 0;
for (int i=0; i<n; i++)
{
if (arr[i] != arr[i+1])
sum = sum + arr[i];
}
return sum;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
int n = sizeof(arr)/sizeof(int);
cout << findSum(arr, n);
return 0;
}
Output:
21
804
Chapter 113. Find sum of non-repeating (distinct) elements in an array
int sum = 0;
// Hash to store all element of array
unordered_set< int > s;
for (int i=0; i<n; i++)
{
if (s.find(arr[i]) == s.end())
{
sum += arr[i];
s.insert(arr[i]);
}
}
return sum;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
int n = sizeof(arr)/sizeof(int);
cout << findSum(arr, n);
return 0;
}
Output:
21
Source
https://www.geeksforgeeks.org/find-sum-non-repeating-distinct-elements-array/
805
Chapter 114
Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
- GeeksforGeeks
Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e]
such that sorting this subarray makes the whole array sorted.
Examples:
1) If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be
able to find that the subarray lies between the indexes 3 and 8.
2) If the input array is [0, 1, 15, 25, 6, 7, 30, 40, 50], your program should be able to find
that the subarray lies between the indexes 2 and 5.
Solution:
1) Find the candidate unsorted subarray
a) Scan from left to right and find the first element which is greater than the next element.
Let s be the index of such an element. In the above example 1, s is 3 (index of 30).
b) Scan from right to left and find the first element (first in right to left order) which is
smaller than the next element (next in right to left order). Let e be the index of such an
element. In the above example 1, e is 7 (index of 31).
2) Check whether sorting the candidate unsorted subarray makes the complete
array sorted or not. If not, then include more elements in the subarray.
a) Find the minimum and maximum values in arr[s..e]. Let minimum and maximum values
be min and max. min and max for [30, 25, 40, 32, 31] are 25 and 40 respectively.
b) Find the first element (if there is any) in arr[0..s-1] which is greater than min, change s
806
Chapter 114. Find the Minimum length Unsorted Subarray, sorting which makes the
complete array sorted
Implementation:
#include<stdio.h>
void printUnsorted(int arr[], int n)
{
int s = 0, e = n-1, i, max, min;
// step 1(a) of above algo
for (s = 0; s < n-1; s++)
{
if (arr[s] > arr[s+1])
break;
}
if (s == n-1)
{
printf("The complete array is sorted");
return;
}
// step 1(b) of above algo
for(e = n - 1; e > 0; e--)
{
if(arr[e] < arr[e-1])
break;
}
// step 2(a) of above algo
max = arr[s]; min = arr[s];
for(i = s + 1; i <= e; i++)
{
if(arr[i] > max)
max = arr[i];
if(arr[i] < min)
min = arr[i];
}
// step 2(b) of above algo
for( i = 0; i < s; i++)
807
Chapter 114. Find the Minimum length Unsorted Subarray, sorting which makes the
complete array sorted
{
if(arr[i] > min)
{
s = i;
break;
}
}
// step 2(c) of above algo
for( i = n -1; i >= e+1; i--)
{
if(arr[i] < max)
{
e = i;
break;
}
}
// step 3 of above algo
printf(" The unsorted subarray which makes the given array "
" sorted lies between the indees %d and %d", s, e);
return;
}
int main()
{
int arr[] = {10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printUnsorted(arr, arr_size);
getchar();
return 0;
}
Java
class Main
{
static void printUnsorted(int arr[], int n)
{
int s = 0, e = n-1, i, max, min;
// step 1(a) of above algo
for (s = 0; s < n-1; s++)
{
if (arr[s] > arr[s+1])
break;
}
if (s == n-1)
808
Chapter 114. Find the Minimum length Unsorted Subarray, sorting which makes the
complete array sorted
{
System.out.println("The complete array is sorted");
return;
}
// step 1(b) of above algo
for(e = n - 1; e > 0; e--)
{
if(arr[e] < arr[e-1])
break;
}
// step 2(a) of above algo
max = arr[s]; min = arr[s];
for(i = s + 1; i <= e; i++)
{
if(arr[i] > max)
max = arr[i];
if(arr[i] < min)
min = arr[i];
}
// step 2(b) of above algo
for( i = 0; i < s; i++)
{
if(arr[i] > min)
{
s = i;
break;
}
}
// step 2(c) of above algo
for( i = n -1; i >= e+1; i--)
{
if(arr[i] < max)
{
e = i;
break;
}
}
// step 3 of above algo
System.out.println(" The unsorted subarray which"+
" makes the given array sorted lies"+
" between the indices "+s+" and "+e);
return;
}
809
Chapter 114. Find the Minimum length Unsorted Subarray, sorting which makes the
complete array sorted
public static void main(String args[])
{
int arr[] = {10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60};
int arr_size = arr.length;
printUnsorted(arr, arr_size);
}
}
Python3
810
Chapter 114. Find the Minimum length Unsorted Subarray, sorting which makes the
complete array sorted
e = i
break
i -= 1
# step 3 of above algo
print ("The unsorted subarray which makes the given array")
print ("sorted lies between the indexes %d and %d"%( s, e))
arr = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60]
arr_size = len(arr)
printUnsorted(arr, arr_size)
# This code is contributed by Shreyanshi Arun
C#
using System;
class GFG
{
static void printUnsorted(int []arr, int n)
{
int s = 0, e = n-1, i, max, min;
// step 1(a) of above algo
for (s = 0; s < n-1; s++)
{
if (arr[s] > arr[s+1])
break;
}
if (s == n-1)
{
Console.Write("The complete " +
"array is sorted");
return;
}
// step 1(b) of above algo
for(e = n - 1; e > 0; e--)
{
if(arr[e] < arr[e-1])
break;
}
// step 2(a) of above algo
max = arr[s]; min = arr[s];
for(i = s + 1; i <= e; i++)
811
Chapter 114. Find the Minimum length Unsorted Subarray, sorting which makes the
complete array sorted
{
if(arr[i] > max)
max = arr[i];
if(arr[i] < min)
min = arr[i];
}
// step 2(b) of above algo
for( i = 0; i < s; i++)
{
if(arr[i] > min)
{
s = i;
break;
}
}
// step 2(c) of above algo
for( i = n -1; i >= e+1; i--)
{
if(arr[i] < max)
{
e = i;
break;
}
}
// step 3 of above algo
Console.Write(" The unsorted subarray which"+
" makes the given array sorted lies \n"+
" between the indices "+s+" and "+e);
return;
}
public static void Main()
{
int []arr = {10, 12, 20, 30, 25, 40,
32, 31, 35, 50, 60};
int arr_size = arr.Length;
printUnsorted(arr, arr_size);
}
}
// This code contributed by Sam007
Output :
812
Chapter 114. Find the Minimum length Unsorted Subarray, sorting which makes the
complete array sorted
Source
https://www.geeksforgeeks.org/minimum-length-unsorted-subarray-sorting-which-makes-the-complete-array-sorted
813
Chapter 115
Asked in : Microsoft
A Naive approach is to consider all subarrays one by one and update indexes of subarray
with sum closest to 0.
814
Chapter 115. Find the Sub-array with sum closest to 0
int start, end, min_sum = INT_MAX;
// Pick a starting point
for (int i = 0; i < n; i++) {
// Consider current starting point
// as a subarray and update minimum
// sum and subarray indexes
int curr_sum = arr[i];
if (min_sum > abs(curr_sum)) {
min_sum = abs(curr_sum);
start = i;
end = i;
}
// Try all subarrays starting with i
for (int j = i + 1; j < n; j++) {
curr_sum = curr_sum + arr[j];
// update minimum sum
// and subarray indexes
if (min_sum > abs(curr_sum)) {
min_sum = abs(curr_sum);
start = i;
end = j;
}
}
}
// Return starting and ending indexes
pair<int, int> p = make_pair(start, end);
return p;
}
// Drivers code
int main()
{
int arr[] = { 2, -5, 4, -6, -3 };
int n = sizeof(arr) / sizeof(arr[0]);
pair<int, int> point = findSubArray(arr, n);
cout << "Subarray starting from ";
cout << point.first << " to " << point.second;
return 0;
}
Output:
815
Chapter 115. Find the Sub-array with sum closest to 0
1. Maintain a Prefix sum array. Also maintain indexes in the prefix sum array.
2. Sort the prefix sum array on the basis of sum.
3. Find the two elements in a prefix sum array with minimum difference.
816
Chapter 115. Find the Sub-array with sum closest to 0
// Store prefix sum with index
for (int i = 1; i <= n; i++) {
pre_sum[i].sum = pre_sum[i-1].sum + arr[i-1];
pre_sum[i].index = i - 1;
}
// Sort on the basis of sum
sort(pre_sum, pre_sum + (n + 1), comparison);
// Find two consecutive elements with minimum difference
for (int i = 1; i <= n; i++) {
int diff = pre_sum[i].sum - pre_sum[i-1].sum;
// Update minimum difference
// and starting and ending indexes
if (min_diff > diff) {
min_diff = diff;
start = pre_sum[i-1].index;
end = pre_sum[i].index;
}
}
// Return starting and ending indexes
pair<int, int> p = make_pair(start + 1, end);
return p;
}
// Drivers code
int main()
{
int arr[] = { 2, 3, -4, -1, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
pair<int, int> point = findSubArray(arr, n);
cout << "Subarray starting from ";
cout << point.first << " to " << point.second;
return 0;
}
Output:
817
Chapter 115. Find the Sub-array with sum closest to 0
Reference:
https://www.careercup.com/question?id=14583859
Source
https://www.geeksforgeeks.org/find-sub-array-sum-closest-0/
818
Chapter 116
Find the largest multiple of 3 from array of digits Set 2 (In O(n) time and O(1) space) -
GeeksforGeeks
Given an array of digits (contain elements from 0 to 9). Find the largest number that can
be made from some or all digits of array and is divisible by 3. The same element may
appear multiple times in the array, but each element in the array may only be used once.
Examples:
1. If remainder is ‘1’ : We have to remove single digit that have remainder ‘1’ or we have
to remove two digit that have remainder ‘2’ ( 2 + 2 => 4 % 3 => ‘1’)
819
Chapter 116. Find the largest multiple of 3 from array of digits Set 2 (In O(n) time and
O(1) space)
2. If remainder is ‘2’ : .We have to remove single digit that have remainder ‘2’ or we have
to remove two digit that have remainder ‘1’ ( 1 + 1 => 2 % 3 => 2 ).
Examples :
Input : arr[] = 5, 5, 5, 7
Sum of digits = 5 + 5 + 7 = 22
Remainder = 22 % 3 = 1
We remove smallest single digit that
has remainder '1'. We remove 7 % 3 = 1
So largest number divisible by 3 is : 555
820
Chapter 116. Find the largest multiple of 3 from array of digits Set 2 (In O(n) time and
O(1) space)
821
Chapter 116. Find the largest multiple of 3 from array of digits Set 2 (In O(n) time and
O(1) space)
if (arr[i]%3 == 2)
{
// If this is first occurrence of remainder 2
if (rem_2[0] == -1)
rem_2[0] = i;
// If second occurrence
else if (rem_2[1] == -1)
rem_2[1] = i;
}
}
if (rem_2[0] != -1 && rem_2[1] != -1)
{
removeAndPrintResult(arr, n, rem_2[0], rem_2[1]);
return true;
}
}
// If remainder is '2', we have to delete either
// one element of remainder '2' or two elements
// of remainder '1'
else if (remainder == 2)
{
int rem_1[2];
rem_1[0] = -1, rem_1[1] = -1;
// traverse array elements
for (int i = 0; i < n; i++)
{
// store first element of remainder '2'
if (arr[i]%3 == 2)
{
removeAndPrintResult(arr, n, i);
return true;
}
if (arr[i]%3 == 1)
{
// If this is first occurrence of remainder 1
if (rem_1[0] == -1)
rem_1[0] = i;
// If second occurrence
else if (rem_1[1] == -1)
rem_1[1] = i;
}
822
Chapter 116. Find the largest multiple of 3 from array of digits Set 2 (In O(n) time and
O(1) space)
}
if (rem_1[0] != -1 && rem_1[1] != -1)
{
removeAndPrintResult(arr, n, rem_1[0], rem_1[1]);
return true;
}
}
cout << "Not possible";
return false;
}
// Driver code
int main()
{
int arr[] = {4 , 4 , 1 , 1 , 1 , 3} ;
int n = sizeof(arr)/sizeof(arr[0]);
largest3Multiple(arr, n);
return 0;
}
Output:
555
Source
https://www.geeksforgeeks.org/find-largest-multiple-3-array-digits-set-2-time-o1-space/
823
Chapter 117
Find the largest number that can be formed with the given digits - GeeksforGeeks
Given an array of integers arr[] representing digits of a number. The task is to write a
program to generate the largest number possible using these digits.
Note: The digits in the array are in between 0 and 9. That is, 0<arr[i]<9.
Examples:
Naive Approach: The naive approach is to sort the given array of digits in descending
order and then form the number using the digits in array keeping the order of digits in the
number same as that of the sorted array.
Time Complexity: O(N logN), where N is the number of digits.
Below is the implementation of above idea:
C++
824
Chapter 117. Find the largest number that can be formed with the given digits
Java
// Java program to generate largest
// possible number with given digits
import java.*;
import java.util.Arrays;
class GFG
{
// Function to generate largest
// possible number with given digits
static int findMaxNum(int arr[], int n)
{
// sort the given array in
// ascending order and then
// traverse into descending
825
Chapter 117. Find the largest number that can be formed with the given digits
Arrays.sort(arr);
int num = arr[0];
// generate the number
for(int i = n – 1; i >= 0; i–)
{
num = num * 10 + arr[i];
}
return num;
}
// Driver code
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 0};
int n = arr.length;
System.out.println(findMaxNum(arr, n));
}
}
// This code is contributed by mits
Python3
826
Chapter 117. Find the largest number that can be formed with the given digits
arr = [1,2,3,4,5,0]
n = len(arr)
print(findMaxNum(arr,n))
PHP
<?php
// PHP program to generate
// largest possible number
// with given digits
// Function to generate
// largest possible number
// with given digits
function findMaxNum(&$arr, $n)
{
// sort the given array
// in descending order
rsort($arr);
$num = $arr[0];
// generate the number
for($i = 1; $i < $n; $i++)
{
$num = $num * 10 + $arr[$i];
}
return $num;
}
// Driver code
$arr = array(1, 2, 3, 4, 5, 0);
$n = sizeof($arr);
echo findMaxNum($arr,$n);
// This code is contributed
// by ChitraNayal
?>
Output:
543210
827
Chapter 117. Find the largest number that can be formed with the given digits
Efficient Approach: An efficient approach is to observe that we have to form the number
using only digits from 0-9. Hence we can create a hash of size 10 to store the number of
occurrences of the digits in the given array into the hash table. Where the key in the hash
table will be digits from 0 to 9 and their values will be the count of their occurrences in the
array.
Finally, print the digits the number of times they occur in descending order starting from
the digit 9.
Below is the implementation of above approach:
C++
828
Chapter 117. Find the largest number that can be formed with the given digits
findMaxNum(arr,n);
return 0;
}
Java
829
Chapter 117. Find the largest number that can be formed with the given digits
int n = arr.length;
findMaxNum(arr,n);
}
}
// This code is contributed
// by ChitraNayal
Python 3
830
Chapter 117. Find the largest number that can be formed with the given digits
C#
// C# program to generate
// largest possible number
// with given digits
using System;
class GFG
{
// Function to generate
// largest possible number
// with given digits
static void findMaxNum(int[] arr,
int n)
{
// Declare a hash array of
// size 10 and initialize
// all the elements to zero
int[] hash = new int[10];
// store the number of
// occurrences of the
// digits in the given
// array into the hash table
for(int i = 0; i < n; i++)
{
hash[arr[i]]++;
}
// Traverse the hash in
// descending order to
// print the required number
for(int i = 9; i >= 0; i--)
{
// Print the number of
// times a digits occurs
for(int j = 0; j < hash[i]; j++)
Console.Write(i);
}
}
// Driver code
public static void Main()
{
831
Chapter 117. Find the largest number that can be formed with the given digits
PHP
<?php
// PHP program to generate
// largest possible number
// with given digits
// Function to generate
// largest possible number
// with given digits
function findMaxNum($arr, $n)
{
// Declare a hash array of
// size 10 and initialize
// all the elements to zero
$hash = array_fill(0, 10, 0);
// store the number of occurrences
// of the digits in the given array
// into the hash table
for($i = 0; $i < $n; $i++)
$hash[$arr[$i]] += 1;
// Traverse the hash in
// descending order to
// print the required number
for($i = 9; $i >= 0; $i--)
// Print the number of
// times a digits occurs
for($j = 0; $j < $hash[$i]; $j++)
echo $i;
}
// Driver code
$arr = array(1, 2, 3, 4, 5, 0);
$n = sizeof($arr);
832
Chapter 117. Find the largest number that can be formed with the given digits
findMaxNum($arr,$n);
// This code is contributed
// by mits
?>
Output:
543210
Source
https://www.geeksforgeeks.org/find-the-largest-number-that-can-be-formed-with-the-given-digits/
833
Chapter 118
Find the minimum and maximum amount to buy all N candies - GeeksforGeeks
In a candy store there are N different types of candies available and the prices of all the
N different types of candies are provided. There is also an attractive offer by candy store.
We can buy a single candy from the store and get at-most K other candies (all are different
types) for free.
1. Find minimum amount of money we have to spend to buy all the N different candies.
2. Find maximum amount of money we have to spend to buy all the N different candies.
In both the cases we must utilize the offer and get maximum possible candies back. If k or
more candies are available, we must take k candies for every candy purchase. If less than k
candies are available, we must take all candies for a candy purchase.
Examples:
834
Chapter 118. Find the minimum and maximum amount to buy all N candies
One important thing to note is, we must use the offer and get maximum candies back
for every candy purchase. So if we want to minimize the money, we must buy candies of
minimum cost and get candies of maximum costs for free. To maximize the money, we must
do reverse. Below is algorithm based on this.
C++
835
Chapter 118. Find the minimum and maximum amount to buy all N candies
Java
836
Chapter 118. Find the minimum and maximum amount to buy all N candies
// And take k candies for free
// from the last
n = n - k;
}
return res;
}
// Function to find the maximum
// amount to buy all candies
static int findMaximum(int arr[], int n, int k)
{
int res = 0, index = 0;
for (int i = n - 1; i >= index; i--)
{
// Buy candy with maximum amount
res += arr[i];
// And get k candies for free from
// the starting
index += k;
}
return res;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 3, 2, 1, 4 };
int n = arr.length;
int k = 2;
Arrays.sort(arr);
System.out.println(findMinimum(arr, n, k) +
" " + findMaximum(arr, n, k));
}
}
// This code is contributed by prerna saini
Python3
# Python implementation
# to find the minimum
# and maximum amount
# Function to find
837
Chapter 118. Find the minimum and maximum amount to buy all N candies
838
Chapter 118. Find the minimum and maximum amount to buy all N candies
C#
839
Chapter 118. Find the minimum and maximum amount to buy all N candies
PHP
<?php
// PHP implementation to find the minimum
// and maximum amount
// Function to find the minimum amount
// to buy all candies
function findMinimum($arr, $n,$k)
{
$res = 0;
for ($i = 0; $i < $n ; $i++)
{
// Buy current candy
$res += $arr[$i];
// And take k candies for free
// from the last
$n = $n - $k;
}
return $res;
}
// Function to find the maximum amount
840
Chapter 118. Find the minimum and maximum amount to buy all N candies
Output:
3 7
Source
https://www.geeksforgeeks.org/find-minimum-maximum-amount-buy-n-candies/
841
Chapter 119
Output: 5
There are maximum 3 guests at time 5.
842
Chapter 119. Find the point where maximum intervals overlap
An Efficient Solution is to use sorting n O(nLogn) time. The idea is to consider all events
(all arrivals and exits) in sorted order. Once we have all events in sorted order, we can trace
the number of guests at any time keeping track of guests that have arrived, but not exited.
Consider the above example.
Below are all events sorted by time. Note that in sorting, if two
events have same time, then arrival is preferred over exit.
Time Event Type Total Number of Guests Present
------------------------------------------------------------
1 Arrival 1
2 Arrival 2
4 Exit 1
5 Arrival 2
5 Arrival 3 // Max Guests
5 Exit 2
9 Exit 1
10 Arrival 2
12 Exit 1
12 Exit 0
843
Chapter 119. Find the point where maximum intervals overlap
// Similar to merge in merge sort to process
// all events in sorted order
while (i < n && j < n)
{
// If next event in sorted order is arrival,
// increment count of guests
if (arrl[i] <= exit[j])
{
guests_in++;
// Update max_guests if needed
if (guests_in > max_guests)
{
max_guests = guests_in;
time = arrl[i];
}
i++; //increment index of arrival array
}
else // If event is exit, decrement count
{ // of guests.
guests_in--;
j++;
}
}
cout << "Maximum Number of Guests = " << max_guests
<< " at time " << time;
}
// Driver program to test above function
int main()
{
int arrl[] = {1, 2, 10, 5, 5};
int exit[] = {4, 5, 12, 9, 12};
int n = sizeof(arrl)/sizeof(arrl[0]);
findMaxGuests(arrl, exit, n);
return 0;
}
Java
844
Chapter 119. Find the point where maximum intervals overlap
845
Chapter 119. Find the point where maximum intervals overlap
}
// This code is contributed by Prerna Saini
C#
846
Chapter 119. Find the point where maximum intervals overlap
PHP
<?php
// PHP Program to find maximum
// guest at any time in a party
function findMaxGuests($arrl, $exit, $n)
{
// Sort arrival and exit arrays
sort($arrl);
sort($exit);
// guests_in indicates number
// of guests at a time
$guests_in = 1;
$max_guests = 1;
$time = $arrl[0];
$i = 1;
$j = 0;
// Similar to merge in merge
// sort to process all events
847
Chapter 119. Find the point where maximum intervals overlap
Output :
848
Chapter 119. Find the point where maximum intervals overlap
#include<bits/stdc++.h>
using namespace std;
void maxOverlap(vector<int>& start, vector<int>& end ){
int n= start.size();
// Finding maximum starting time O(n)
int maxa=*max_element(start.begin(),start.end());
//Finding maximum ending time O(n)
int maxb=*max_element(end.begin(),end.end());
int maxc=max(maxa,maxb);
int x[maxc+2];memset(x,0,sizeof x);
int cur=0,idx;
for(int i=0;i<n;i++)// Creating and auxiliary array O(n)
{ //Lazy addition
++x[start[i]];
--x[end[i]+1];
}
int maxy=INT_MIN;
//Lazily Calculating value at index i O(n)
for(int i=0;i<=maxc;i++)
{
cur+=x[i];if(maxy<cur){maxy=cur;idx=i;}
}
cout<<"Maximum value is "<<maxy<<" at position "<<idx<<endl;
}
// DRIVER FUNCTION
849
Chapter 119. Find the point where maximum intervals overlap
int main()
{
vector<int> start={13,28,29,14,40,17,3},
end={107,95,111,105,70,127,74};
maxOverlap(start,end);
return 0;
}
Java
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void maxOverlap(int []start,int [] end ,int n)
{
// Finding maximum starting time
int maxa = Arrays.stream(start).max().getAsInt();
// Finding maximum ending time
int maxb = Arrays.stream(end).max().getAsInt();
int maxc=Math.max(maxa,maxb);
int []x = new int[maxc+2];
Arrays.fill(x, 0);
int cur=0,idx=0;
// CREATING AN AUXILIARY ARRAY
for(int i=0;i<n;i++)
{// Lazy addition
++x[start[i]];
--x[end[i]+1];
}
int maxy=Integer.MIN_VALUE;
//Lazily Calculating value at index i
for(int i=0;i<=maxc;i++)
{
cur+=x[i];if(maxy<cur){maxy=cur;idx=i;}
}
System.out.println("Maximum value is:"+
maxy+" at position: "+idx+"");
850
Chapter 119. Find the point where maximum intervals overlap
}
public static void main(String[] args) {// Driver function
int [] start = new int[]{13, 28, 29, 14, 40, 17, 3 };
int [] end = new int[]{107, 95, 111, 105, 70, 127, 74};
int n=start.length;
maxOverlap(start,end,n);
}
}
Python3
import sys
def maxOverlap(start,end):
n= len(start)
maxa = max(start)# Finding maximum starting time
maxb = max(end) # Finding maximum ending time
maxc=max(maxa,maxb)
x =(maxc+2)*[0]
cur=0; idx=0
for i in range(0,n) :# CREATING AN AUXILIARY ARRAY
x[start[i]]+=1 # Lazy addition
x[end[i]+1]-=1
maxy=-1
#Lazily Calculating value at index i
for i in range(0,maxc+1):
cur+=x[i]
if maxy<cur :
maxy=cur
idx=i
print("Maximum value is: {0:d}".format(maxy),
" at position: {0:d}".format(idx))
if __name__ == "__main__":
start=[13,28,29,14,40,17,3]
end=[107,95,111,105,70,127,74]
maxOverlap(start,end)
851
Chapter 119. Find the point where maximum intervals overlap
Source
https://www.geeksforgeeks.org/find-the-point-where-maximum-intervals-overlap/
852
Chapter 120
#include<bits/stdc++.h>
/* Return 1 if arr2[] is a subset of
arr1[] */
bool isSubset(int arr1[], int arr2[],
int m, int n)
{
853
Chapter 120. Find whether an array is subset of another array Added Method 3
int i = 0;
int j = 0;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
if(arr2[i] == arr1[j])
break;
}
/* If the above inner loop was
not broken at all then arr2[i]
is not present in arr1[] */
if (j == m)
return 0;
}
/* If we reach here then all
elements of arr2[] are present
in arr1[] */
return 1;
}
// Driver code
int main()
{
int arr1[] = {11, 1, 13, 21, 3, 7};
int arr2[] = {11, 3, 7, 1};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
if(isSubset(arr1, arr2, m, n))
printf("arr2[] is subset of arr1[] ");
else
printf("arr2[] is not a subset of arr1[]");
getchar();
return 0;
}
Java
854
Chapter 120. Find whether an array is subset of another array Added Method 3
C#
855
Chapter 120. Find whether an array is subset of another array Added Method 3
856
Chapter 120. Find whether an array is subset of another array Added Method 3
}
// This code is contributed by Sam007
PHP
<?php
/* Return 1 if arr2[] is a subset of
arr1[] */
function isSubset($arr1, $arr2, $m, $n)
{
$i = 0;
$j = 0;
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $m; $j++)
{
if($arr2[$i] == $arr1[$j])
break;
}
/* If the above inner loop was
not broken at all then arr2[i]
is not present in arr1[] */
if ($j == $m)
return 0;
}
/* If we reach here then all
elements of arr2[] are present
in arr1[] */
return 1;
}
// Driver code
$arr1 = array(11, 1, 13, 21, 3, 7);
$arr2 = array(11, 3, 7, 1);
$m = count($arr1);
$n = count($arr2);
if(isSubset($arr1, $arr2, $m, $n))
echo "arr2[] is subset of arr1[] ";
else
echo "arr2[] is not a subset of arr1[]";
// This code is contributed by anuj_67.
?>
857
Chapter 120. Find whether an array is subset of another array Added Method 3
Output:
#include<stdio.h>
/* Fucntion prototypes */
void quickSort(int *arr, int si, int ei);
int binarySearch(int arr[], int low, int high, int x);
/* Return 1 if arr2[] is a subset of arr1[] */
bool isSubset(int arr1[], int arr2[], int m, int n)
{
int i = 0;
quickSort(arr1, 0, m-1);
for (i=0; i<n; i++)
{
if (binarySearch(arr1, 0, m-1, arr2[i]) == -1)
return 0;
}
/* If we reach here then all elements of arr2[]
are present in arr1[] */
return 1;
}
/* FOLLOWING FUNCTIONS ARE ONLY FOR SEARCHING AND SORTING PURPOSE */
/* Standard Binary Search function*/
int binarySearch(int arr[], int low, int high, int x)
{
if(high >= low)
{
int mid = (low + high)/2; /*low + (high - low)/2;*/
858
Chapter 120. Find whether an array is subset of another array Added Method 3
/* Check if arr[mid] is the first occurrence of x.
arr[mid] is first occurrence if x is one of the following
is true:
(i) mid == 0 and arr[mid] == x
(ii) arr[mid-1] < x and arr[mid] == x
*/
if(( mid == 0 || x > arr[mid-1]) && (arr[mid] == x))
return mid;
else if(x > arr[mid])
return binarySearch(arr, (mid + 1), high, x);
else
return binarySearch(arr, low, (mid -1), x);
}
return -1;
}
void exchange(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int partition(int A[], int si, int ei)
{
int x = A[ei];
int i = (si - 1);
int j;
for (j = si; j <= ei - 1; j++)
{
if(A[j] <= x)
{
i++;
exchange(&A[i], &A[j]);
}
}
exchange (&A[i + 1], &A[ei]);
return (i + 1);
}
/* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
859
Chapter 120. Find whether an array is subset of another array Added Method 3
Java
class Main
{
/* Return true if arr2[] is a subset of arr1[] */
static boolean isSubset(int arr1[], int arr2[], int m, int n)
{
int i = 0;
sort(arr1, 0, m-1);
for (i=0; i<n; i++)
{
if (binarySearch(arr1, 0, m-1, arr2[i]) == -1)
return false;
}
/* If we reach here then all elements of arr2[]
are present in arr1[] */
return true;
}
860
Chapter 120. Find whether an array is subset of another array Added Method 3
/* FOLLOWING FUNCTIONS ARE ONLY FOR SEARCHING AND SORTING PURPOSE */
/* Standard Binary Search function*/
static int binarySearch(int arr[], int low, int high, int x)
{
if(high >= low)
{
int mid = (low + high)/2; /*low + (high - low)/2;*/
/* Check if arr[mid] is the first occurrence of x.
arr[mid] is first occurrence if x is one of the following
is true:
(i) mid == 0 and arr[mid] == x
(ii) arr[mid-1] < x and arr[mid] == x
*/
if(( mid == 0 || x > arr[mid-1]) && (arr[mid] == x))
return mid;
else if(x > arr[mid])
return binarySearch(arr, (mid + 1), high, x);
else
return binarySearch(arr, low, (mid -1), x);
}
return -1;
}
/* This function takes last element as pivot,
places the pivot element at its correct
position in sorted array, and places all
smaller (smaller than pivot) to left of
pivot and all greater elements to right
of pivot */
static int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
861
Chapter 120. Find whether an array is subset of another array Added Method 3
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
static void sort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
public static void main(String args[])
{
int arr1[] = {11, 1, 13, 21, 3, 7};
int arr2[] = {11, 3, 7, 1};
int m = arr1.length;
int n = arr2.length;
if(isSubset(arr1, arr2, m, n))
System.out.print("arr2[] is subset of arr1[] ");
else
System.out.print("arr2[] is not a subset of arr1[]");
}
}
Time Complexity: O(mLogm + nLogm). Please note that this will be the complexity if an
mLogm algorithm is used for sorting which is not the case in above code. In above code
Quick Sort is sued and worst case time complexity of Quick Sort is O(m^2)
862
Chapter 120. Find whether an array is subset of another array Added Method 3
#include <bits/stdc++.h>
using namespace std;
/* Return 1 if arr2[] is a subset of arr1[] */
bool isSubset(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
if (m < n)
return 0;
sort(arr1, arr1 + m);
sort(arr2, arr2 + n);
while (i < n && j < m )
{
if( arr1[j] <arr2[i] )
j++;
else if( arr1[j] == arr2[i] )
{
j++;
i++;
}
else if( arr1[j] > arr2[i] )
return 0;
}
return (i < n)? false : true;
}
/*Driver program to test above functions */
int main()
{
int arr1[] = {11, 1, 13, 21, 3, 7};
int arr2[] = {11, 3, 7, 1};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
if(isSubset(arr1, arr2, m, n))
printf("arr2[] is subset of arr1[] ");
else
863
Chapter 120. Find whether an array is subset of another array Added Method 3
Java
864
Chapter 120. Find whether an array is subset of another array Added Method 3
int m = arr1.length;
int n = arr2.length;
if(isSubset(arr1, arr2, m, n))
System.out.println("arr2 is a subset of arr1");
else
System.out.println("arr2 is not a subset of arr1");
}
}
// This code is contributed by Kamal Rawal
C#
865
Chapter 120. Find whether an array is subset of another array Added Method 3
if( i < n )
return false;
else
return true;
}
// Driver Code
public static void Main()
{
int []arr1 = {11, 1, 13, 21, 3, 7};
int []arr2 = {11, 3, 7, 1};
int m = arr1.Length;
int n = arr2.Length;
if(isSubset(arr1, arr2, m, n))
Console.Write("arr2 is a subset of arr1");
else
Console.Write("arr2 is not a subset of arr1");
}
}
// This code is contributed by nitin mittal.
PHP
<?php
/* Return 1 if arr2[] is a subset of arr1[] */
function isSubset( $arr1, $arr2, $m, $n)
{
$i = 0; $j = 0;
if ($m < $n)
return 0;
sort($arr1);
sort($arr2);
while ($i < $n and $j < $m )
{
if( $arr1[$j] <$arr2[$i] )
$j++;
else if( $arr1[$j] == $arr2[$i] )
{
$j++;
$i++;
866
Chapter 120. Find whether an array is subset of another array Added Method 3
}
else if( $arr1[$j] > $arr2[$i] )
return 0;
}
return ($i < $n) ? false : true;
}
/*Driver program to test above functions */
$arr1 = array(11, 1, 13, 21, 3, 7);
$arr2 = array(11, 3, 7, 1);
$m = count($arr1);
$n = count($arr2);
if(isSubset($arr1, $arr2, $m, $n))
echo "arr2[] is subset of arr1[] ";
else
echo "arr2[] is not a subset of arr1[] ";
// This code is contributed by anuj_67.
?>
Output:
Time Complexity: O(mLogm + nLogn) which is better than method 2. Please note that
this will be the complexity if an nLogn algorithm is used for sorting both arrays which is not
the case in above code. In above code Quick Sort is sued and worst case time complexity of
Quick Sort is O(n^2)
Method 4 (Use Hashing)
1) Create a Hash Table for all the elements of arr1[].
2) Traverse arr2[] and search for each element of arr2[] in the Hash Table. If element is not
found then return 0.
3) If all elements are found then return 1.
867
Chapter 120. Find whether an array is subset of another array Added Method 3
{
HashSet<Integer> hset= new HashSet<>();
// hset stores all the values of arr1
for(int i = 0; i < m; i++)
{
if(!hset.contains(arr1[i]))
hset.add(arr1[i]);
}
// loop to check if all elements of arr2 also
// lies in arr1
for(int i = 0; i < n; i++)
{
if(!hset.contains(arr2[i]))
return false;
}
return true;
}
public static void main(String[] args)
{
int arr1[] = {11, 1, 13, 21, 3, 7};
int arr2[] = {11, 3, 7, 1};
int m = arr1.length;
int n = arr2.length;
if(isSubset(arr1, arr2, m, n))
System.out.println("arr2 is a subset of arr1");
else
System.out.println("arr2 is not a subset of arr1");
}
}
// This code is contributed by Kamal Rawal
Note that method 1, method 2 and method 4 don’t handle the cases when we have duplicates
in arr2[]. For example, {1, 4, 4, 2} is not a subset of {1, 4, 2}, but these methods will print
it as a subset.
Improved By : Sam007, nitin mittal, vt_m
868
Chapter 120. Find whether an array is subset of another array Added Method 3
Source
https://www.geeksforgeeks.org/find-whether-an-array-is-subset-of-another-array-set-1/
869
Chapter 121
Find whether it is possible to make array elements same using one external number - Geeks-
forGeeks
Given an Array, three operations can be performed using any external number x.
Add x to an element once
Subtract x from an element once
Perform no operation on the element
Find whether there exists a number X, such that if the above operations are performed with
the number X, the resulting array has equal elements.
If the number exists, print “YES” and the value, space separated, else print “NO”
Examples:
Input : [1, 1, 3, 5, 5]
Output : YES, x = 2
Explanation : The number 2 can be added to the
first two elements and can be subtracted from
the last two elements to obtain a common element
3 throughout the array
Input : [1, 3, 5, 7, 9]
Output : NO
The idea is to form groups of unique elements from given array. Following cases arise :
870
Chapter 121. Find whether it is possible to make array elements same using one external
number
• If difference between mid and max is same as difference between mid and min,
answer is YES with x = difference between mid and max or mid and min.
• Otherwise answer is NO.
871
Chapter 121. Find whether it is possible to make array elements same using one external
number
print("NO")
# Driver code
array = [55, 52, 52, 49, 52]
canEqualise(array)
Output:
YES 3
Source
https://www.geeksforgeeks.org/find-whether-possible-make-array-elements-using-one-external-number/
872
Chapter 122
Generic Implementation of
QuickSort Algorithm in C
We use void* to implement generic quicksort function in C. void* does not know how much
bytes of memory it has to occupy in memory space. It must be casted to any other data
type like int*, char* before doing any operation on it.
Example: when we declare int var; compiler knows that it has occupy 4 bytes of memory
but void does not know how much bytes of memory it has to occupy.
We will also use a pointer to function that will point to a function which is dependent to
different types of data i.e and this function will be defined by the user according to there
need.
Below is the image representation of void* in memory before and after casting it to any
particular data type for better understanding.
Void* pt in Memory :
873
Chapter 122. Generic Implementation of QuickSort Algorithm in C
874
Chapter 122. Generic Implementation of QuickSort Algorithm in C
875
Chapter 122. Generic Implementation of QuickSort Algorithm in C
int* p = b;
_qsort(a, sizeof(char*), 0, 8, (int (*)(void*, void*))(cmpstr));
_qsort(p, sizeof(int), 0, 6, (int (*)(void*, void*))(cmpnum));
for (int i = 0; i < 9; i++)
printf("%s ", a[i]);
printf("\n");
for (int i = 0; i < 7; i++)
printf("%d ", b[i]);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/generic-implementation-of-quicksort-algorithm-in-c/
876
Chapter 123
877
Chapter 123. Given a number, find the next smallest palindrome
to two elements around the middle element in case of n being odd). We one by one move i
and j away from each other.
Step 1. Initially, ignore the part of left side which is same as the corresponding part of right
side. For example, if the number is “8 3 4 2 2 4 6 9�, we ignore the middle four elements.
i now points to element 3 and j now points to element 6.
Step 2. After step 1, following cases arise:
Case 1: Indices i & j cross the boundary.
This case occurs when the input number is palindrome. In this case, we just add 1 to the
middle digit (or digits in case n is even) propagate the carry towards MSB digit of left side
and simultaneously copy mirror of the left side to the right side.
For example, if the given number is “1 2 9 2 1”, we increment 9 to 10 and propagate the
carry. So the number becomes “1 3 0 3 1”
Case 2: There are digits left between left side and right side which are not same. So, we
just mirror the left side to the right side & try to minimize the number formed to guarantee
the next smallest palindrome.
In this case, there can be two sub-cases.
2.1) Copying the left side to the right side is sufficient, we don’t need to increment any
digits and the result is just mirror of left side. Following are some examples of this sub-case.
Next palindrome for “7 8 3 3 2 2� is “7 8 3 3 8 7”
Next palindrome for “1 2 5 3 2 2� is “1 2 5 5 2 1”
Next palindrome for “1 4 5 8 7 6 7 8 3 2 2� is “1 4 5 8 7 6 7 8 5 4 1”
How do we check for this sub-case? All we need to check is the digit just after the ignored
part in step 1. This digit is highlighted in above examples. If this digit is greater than the
corresponding digit in right side digit, then copying the left side to the right side is sufficient
and we don’t need to do anything else.
2.2) Copying the left side to the right side is NOT sufficient. This happens when the above
defined digit of left side is smaller. Following are some examples of this case.
Next palindrome for “7 1 3 3 2 2� is “7 1 4 4 1 7”
Next palindrome for “1 2 3 4 6 2 8� is “1 2 3 5 3 2 1”
Next palindrome for “9 4 1 8 7 9 7 8 3 2 2� is “9 4 1 8 8 0 8 8 1 4 9”
We handle this subcase like Case 1. We just add 1 to the middle digit (or digits in case n
is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror
of the left side to the right side.
C++
#include <stdio.h>
// A utility function to print an array
void printArray (int arr[], int n);
// A utility function to check if num has all 9s
int AreAll9s (int num[], int n );
// Returns next palindrome of a given number num[].
878
Chapter 123. Given a number, find the next smallest palindrome
879
Chapter 123. Given a number, find the next smallest palindrome
else
j = mid;
// Add 1 to the rightmost digit of the left side, propagate the carry
// towards MSB digit and simultaneously copying mirror of the left side
// to the right side.
while (i >= 0)
{
num[i] += carry;
carry = num[i] / 10;
num[i] %= 10;
num[j++] = num[i--]; // copy mirror to right
}
}
}
// The function that prints next palindrome of a given number num[]
// with n digits.
void generateNextPalindrome( int num[], int n )
{
int i;
printf("Next palindrome is:");
// Input type 1: All the digits are 9, simply o/p 1
// followed by n-1 0's followed by 1.
if( AreAll9s( num, n ) )
{
printf( "1 ");
for( i = 1; i < n; i++ )
printf( "0 " );
printf( "1" );
}
// Input type 2 and 3
else
{
generateNextPalindromeUtil ( num, n );
// print the result
printArray (num, n);
}
}
// A utility function to check if num has all 9s
int AreAll9s( int* num, int n )
{
int i;
880
Chapter 123. Given a number, find the next smallest palindrome
Java
881
Chapter 123. Given a number, find the next smallest palindrome
882
Chapter 123. Given a number, find the next smallest palindrome
{
num[i] = num[i] + carry;
carry = num[i] / 10;
num[i] %= 10;
num[j] = num[i];// copy mirror to right
i--;
j++;
}
}
}
// The function that prints next palindrome
// of a given number num[] with n digits.
static void generateNextPalindrome(int num[], int n)
{
System.out.println("Next Palindrome is:");
// Input type 1: All the digits are 9,
// simply o/p 1 followed by n-1 0's
// followed by 1.
if (isAll9(num, n)) {
System.out.print("1");
for (int i = 0; i < n - 1; i++)
System.out.print("0");
System.out.println("1");
}
// Input type 2 and 3
else {
generateNextPalindromeUtil(num, n);
printarray(num);
}
}
// A utility function to check if num has all 9s
static boolean isAll9(int num[], int n) {
for (int i = 0; i < n; i++)
if (num[i] != 9)
return false;
return true;
}
/* Utility that prints out an array on a line */
static void printarray(int num[]) {
for (int i = 0; i < num.length; i++)
System.out.print(num[i]);
883
Chapter 123. Given a number, find the next smallest palindrome
System.out.println();
}
public static void main(String[] args)
{
int num[] = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 };
generateNextPalindrome(num, num.length);
}
}
Python3
884
Chapter 123. Given a number, find the next smallest palindrome
# Handle the case where middle
# digit(s) must be incremented.
# This part of code is for CASE 1 and CASE 2.2
if (leftsmaller == True) :
carry = 1
i = mid - 1
# If there are odd digits, then increment
# the middle digit and store the carry
if (n%2 == 1) :
num[mid] += carry
carry = int(num[mid] / 10 )
num[mid] %= 10
j = mid + 1
else:
j = mid
# Add 1 to the rightmost digit of the
# left side, propagate the carry
# towards MSB digit and simultaneously
# copying mirror of the left side
# to the right side.
while (i >= 0) :
num[i] += carry
carry = num[i] / 10
num[i] %= 10
num[j] = num[i] # copy mirror to right
j+=1
i-=1
# The function that prints next
# palindrome of a given number num[]
# with n digits.
def generateNextPalindrome(num, n ) :
print("\nNext palindrome is:")
# Input type 1: All the digits are 9, simply o/p 1
# followed by n-1 0's followed by 1.
if( AreAll9s( num, n ) == True) :
print( "1")
for i in range(1, n):
885
Chapter 123. Given a number, find the next smallest palindrome
print( "0" )
print( "1")
# Input type 2 and 3
else:
generateNextPalindromeUtil ( num, n )
# print the result
printArray (num, n)
# A utility function to check if num has all 9s
def AreAll9s(num, n ):
for i in range(1, n):
if( num[i] != 9 ) :
return 0
return 1
# Utility that prints out an array on a line
def printArray(arr, n):
for i in range(0, n):
print(int(arr[i]),end=" ")
print()
# Driver Program to test above function
if __name__ == "__main__":
num = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2]
n = len(num)
generateNextPalindrome( num, n )
# This code is contributed by Smitha Dinesh Semwal
C#
886
Chapter 123. Given a number, find the next smallest palindrome
// end of left side is always 'mid -1'
int i = mid - 1;
// Begining of right side depends
// if n is odd or even
int j = (n % 2 == 0) ? mid : mid + 1;
// A bool variable to check if copy of left
// side to right
// is sufficient or not
bool leftsmaller = false;
// Initially, ignore the middle same digits
while (i >= 0 && num[i] == num[j])
{
i--;
j++;
}
// Find if the middle digit(s) need to
// be incremented or not (or copying left
// side is not sufficient)
if (i < 0 || num[i] < num[j])
{
leftsmaller = true;
}
// Copy the mirror of left to tight
while (i >= 0)
{
num[j++] = num[i--];
}
// Handle the case where middle digit(s)
// must be incremented. This part of code
// is for CASE 1 and CASE 2.2
if (leftsmaller)
{
int carry = 1;
// If there are odd digits, then increment
// the middle digit and store the carry
if (n % 2 == 1) {
num[mid] += 1;
carry = num[mid] / 10;
num[mid] %= 10;
}
887
Chapter 123. Given a number, find the next smallest palindrome
i = mid - 1;
j = (n % 2 == 0 ? mid : mid + 1);
// Add 1 to the rightmost digit of the left
// side, propagate the carry towards MSB digit
// and simultaneously copying mirror of the
// left side to the right side.
while (i >= 0)
{
num[i] = num[i] + carry;
carry = num[i] / 10;
num[i] %= 10;
num[j] = num[i];// copy mirror to right
i--;
j++;
}
}
}
// The function that prints next palindrome
// of a given number num[] with n digits.
static void generateNextPalindrome(int []num, int n)
{
Console.WriteLine("Next Palindrome is:");
// Input type 1: All the digits are 9,
// simply o/p 1 followed by n-1 0's
// followed by 1.
if (isAll9(num, n)) {
Console.Write("1");
for (int i = 0; i < n - 1; i++)
Console.Write("0");
Console.Write("1");
}
// Input type 2 and 3
else {
generateNextPalindromeUtil(num, n);
printarray(num);
}
}
// A utility function to check if num has all 9s
static bool isAll9(int[] num, int n) {
for (int i = 0; i < n; i++)
if (num[i] != 9)
888
Chapter 123. Given a number, find the next smallest palindrome
return false;
return true;
}
/* Utility that prints out an array on a line */
static void printarray(int []num) {
for (int i = 0; i < num.Length; i++)
Console.Write(num[i]+ " ");
Console.Write(" ");
}
// Driver code
public static void Main()
{
int []num = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 };
generateNextPalindrome(num, num.Length);
}
}
// This code is contributed by Smitha.
PHP
<?php
// PHP program to find next
// smallest palindrome
// Returns next palindrome
// of a given number num[].
// This function is for
// input type 2 and 3
function generateNextPalindromeUtil($num, $n)
{
$mid = (int)($n / 2);
// end of left side
// is always 'mid -1'
$i = $mid - 1;
// Begining of right
// side depends if n
// is odd or even
$j = ($n % 2 == 0) ?
$mid : ($mid + 1);
// A bool variable to check
// if copy of left side to
// right is sufficient or not
889
Chapter 123. Given a number, find the next smallest palindrome
$leftsmaller = false;
// Initially, ignore the
// middle same digits
while ($i >= 0 &&
$num[$i] == $num[$j])
{
$i--;
$j++;
}
// Find if the middle digit(s)
// need to be incremented or
// not (or copying left side
// is not sufficient)
if ($i < 0 || $num[$i] < $num[$j])
{
$leftsmaller = true;
}
// Copy the mirror
// of left to tight
while ($i >= 0)
{
$num[$j++] = $num[$i--];
}
// Handle the case where
// middle digit(s) must be
// incremented. This part
// of code is for CASE 1
// and CASE 2.2
if ($leftsmaller)
{
$carry = 1;
// If there are odd digits,
// then increment the middle
// digit and store the carry
if ($n % 2 == 1)
{
$num[$mid] += 1;
$carry = (int)($num[$mid] / 10);
$num[$mid] %= 10;
}
$i = $mid - 1;
$j = ($n % 2 == 0 ?
$mid : $mid + 1);
890
Chapter 123. Given a number, find the next smallest palindrome
// Add 1 to the rightmost digit
// of the left side, propagate
// the carry towards MSB digit
// and simultaneously copying
// mirror of the left side to
// the right side.
while ($i >= 0)
{
$num[$i] = $num[$i] + $carry;
$carry = (int)($num[$i] / 10);
$num[$i] %= 10;
// copy mirror to right
$num[$j] = $num[$i];
$i--;
$j++;
}
}
return $num;
}
// The function that prints
// next palindrome of a given
// number num[] with n digits.
function generateNextPalindrome($num, $n)
{
echo "Next Palindrome is:\n";
// Input type 1: All the
// digits are 9, simply
// o/p 1 followed by n-1
// 0's followed by 1.
if (isAll9($num, $n))
{
echo "1";
for ($i = 0; $i < $n - 1; $i++)
echo "0";
echo "1";
}
// Input type 2 and 3
else
{
$num = generateNextPalindromeUtil($num, $n);
printarray($num);
891
Chapter 123. Given a number, find the next smallest palindrome
}
}
// A utility function to
// check if num has all 9s
function isAll9($num, $n)
{
for ($i = 0; $i < $n; $i++)
if ($num[$i] != 9)
return false;
return true;
}
/* Utility that prints out
an array on a line */
function printarray($num)
{
for ($i = 0;
$i < count($num); $i++)
echo $num[$i];
echo "\n";
}
// Driver code
$num = array(9, 4, 1, 8, 7,
9, 7, 8, 3, 2, 2);
generateNextPalindrome($num,
count($num));
// This code is contributed by mits.
?>
Output:
Source
https://www.geeksforgeeks.org/given-a-number-find-next-smallest-palindrome-larger-than-this-number/
892
Chapter 124
Given a sorted array and a number x, find the pair in array whose sum is closest to x -
GeeksforGeeks
Given a sorted array and a number x, find a pair in array whose sum is closest to x.
Examples:
A simple solution is to consider every pair and keep track of closest pair (absolute difference
between pair sum and x is minimum). Finally print the closest pair. Time complexity of
this solution is O(n2 )
An efficient solution can find the pair in O(n) time. The idea is similar to method 2 of
thispost. Following is detailed algorithm.
893
Chapter 124. Given a sorted array and a number x, find the pair in array whose sum is
closest to x
// Simple C++ program to find the pair with sum closest to a given no.
#include <iostream>
#include <climits>
#include <cstdlib>
using namespace std;
// Prints the pair with sum closest to x
void printClosest(int arr[], int n, int x)
{
int res_l, res_r; // To store indexes of result pair
// Initialize left and right indexes and difference between
// pair sum and x
int l = 0, r = n-1, diff = INT_MAX;
// While there are elements between l and r
while (r > l)
{
// Check if this pair is closer than the closest pair so far
if (abs(arr[l] + arr[r] - x) < diff)
{
res_l = l;
res_r = r;
diff = abs(arr[l] + arr[r] - x);
}
// If this pair has more sum, move to smaller values.
if (arr[l] + arr[r] > x)
r--;
else // Move to larger values
l++;
}
cout <<" The closest pair is " << arr[res_l] << " and " << arr[res_r];
}
// Driver program to test above functions
int main()
{
894
Chapter 124. Given a sorted array and a number x, find the pair in array whose sum is
closest to x
Java
895
Chapter 124. Given a sorted array and a number x, find the pair in array whose sum is
closest to x
{
int arr[] = {10, 22, 28, 29, 30, 40}, x = 54;
int n = arr.length;
printClosest(arr, n, x);
}
}
/*This code is contributed by Devesh Agrawal*/
Python3
896
Chapter 124. Given a sorted array and a number x, find the pair in array whose sum is
closest to x
print('The closest pair is {} and {}'
.format(arr[res_l], arr[res_r]))
# Driver code to test above
if __name__ == "__main__":
arr = [10, 22, 28, 29, 30, 40]
n = len(arr)
x=54
printClosest(arr, n, x)
# This code is contributed by Tuhin Patra
C#
897
Chapter 124. Given a sorted array and a number x, find the pair in array whose sum is
closest to x
r--;
else // Move to larger values
l++;
}
Console.Write(" The closest pair is " +
arr[res_l] + " and " + arr[res_r]);
}
// Driver program to test above function
public static void Main()
{
int []arr = {10, 22, 28, 29, 30, 40};
int x = 54;
int n = arr.Length;
printClosest(arr, n, x);
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// Simple PHP program to find the
// pair with sum closest to a
// given no.
// Prints the pair with
// sum closest to x
function printClosest($arr, $n, $x)
{
// To store indexes
// of result pair
$res_l;
$res_r;
// Initialize left and right
// indexes and difference between
// pair sum and x
$l = 0;
$r = $n - 1;
$diff = PHP_INT_MAX;
// While there are elements
// between l and r
898
Chapter 124. Given a sorted array and a number x, find the pair in array whose sum is
closest to x
Output:
This article is contributed by Harsh. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : nitin mittal, vt_m, TuhinPatra
899
Chapter 124. Given a sorted array and a number x, find the pair in array whose sum is
closest to x
Source
https://www.geeksforgeeks.org/given-sorted-array-number-x-find-pair-array-whose-sum-closest-x/
900
Chapter 125
The idea is to create a graph of characters and then find topological sorting of the created
graph. Following are the detailed steps.
1) Create a graph g with number of vertices equal to the size of alphabet in the given alien
language. For example, if the alphabet size is 5, then there can be 5 characters in words.
Initially there are no edges in graph.
2) Do following for every pair of adjacent words in given sorted array.
…..a) Let the current pair of words be word1 and word2. One by one compare characters of
both words and find the first mismatching characters.
…..b) Create an edge in g from mismatching character of word1 to that of word2.
3) Print topological sorting of the above created graph.
901
Chapter 125. Given a sorted dictionary of an alien language, find order of characters
902
Chapter 125. Given a sorted dictionary of an alien language, find order of characters
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
topologicalSortUtil(*i, visited, Stack);
// Push current vertex to stack which stores result
Stack.push(v);
}
// The function to do Topological Sort. It uses recursive topologicalSortUtil()
void Graph::topologicalSort()
{
stack<int> Stack;
// Mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Call the recursive helper function to store Topological Sort
// starting from all vertices one by one
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, Stack);
// Print contents of stack
while (Stack.empty() == false)
{
cout << (char) ('a' + Stack.top()) << " ";
Stack.pop();
}
}
int min(int x, int y)
{
return (x < y)? x : y;
}
// This function fidns and prints order of characer from a sorted
// array of words. n is size of words[]. alpha is set of possible
// alphabets.
// For simplicity, this function is written in a way that only
// first 'alpha' characters can be there in words array. For
// example if alpha is 7, then words[] should have only 'a', 'b',
// 'c' 'd', 'e', 'f', 'g'
void printOrder(string words[], int n, int alpha)
{
// Create a graph with 'aplha' edges
903
Chapter 125. Given a sorted dictionary of an alien language, find order of characters
Graph g(alpha);
// Process all adjacent pairs of words and create a graph
for (int i = 0; i < n-1; i++)
{
// Take the current two words and find the first mismatching
// character
string word1 = words[i], word2 = words[i+1];
for (int j = 0; j < min(word1.length(), word2.length()); j++)
{
// If we find a mismatching character, then add an edge
// from character of word1 to that of word2
if (word1[j] != word2[j])
{
g.addEdge(word1[j]-'a', word2[j]-'a');
break;
}
}
}
// Print topological sort of the above created graph
g.topologicalSort();
}
// Driver program to test above functions
int main()
{
string words[] = {"caa", "aaa", "aab"};
printOrder(words, 3, 3);
return 0;
}
Java
904
Chapter 125. Given a sorted dictionary of an alien language, find order of characters
905
Chapter 125. Given a sorted dictionary of an alien language, find order of characters
// Call the recursive helper function to store Topological
// Sort starting from all vertices one by one
for (int i = 0; i < getNoOfVertices(); i++)
{
if (!visited[i])
{
topologicalSortUtil(i, visited, stack);
}
}
// Print contents of stack
while (!stack.isEmpty())
{
System.out.print((char)('a' + stack.pop()) + " ");
}
}
}
public class OrderOfCharacters
{
// This function fidns and prints order
// of characer from a sorted array of words.
// alpha is number of possible alphabets
// starting from 'a'. For simplicity, this
// function is written in a way that only
// first 'alpha' characters can be there
// in words array. For example if alpha
// is 7, then words[] should contain words
// having only 'a', 'b','c' 'd', 'e', 'f', 'g'
private static void printOrder(String[] words, int alpha)
{
// Create a graph with 'aplha' edges
Graph graph = new Graph(alpha);
for (int i = 0; i < words.length - 1; i++)
{
// Take the current two words and find the first mismatching
// character
String word1 = words[i];
String word2 = words[i+1];
for (int j = 0; j < Math.min(word1.length(), word2.length()); j++)
{
// If we find a mismatching character, then add an edge
// from character of word1 to that of word2
if (word1.charAt(j) != word2.charAt(j))
{
graph.addEdge(word1.charAt(j) - 'a', word2.charAt(j)- 'a');
906
Chapter 125. Given a sorted dictionary of an alien language, find order of characters
break;
}
}
}
// Print topological sort of the above created graph
graph.topologicalSort();
}
// Driver program to test above functions
public static void main(String[] args)
{
String[] words = {"caa", "aaa", "aab"};
printOrder(words, 3);
}
}
//Contributed by Harikrishnan Rajan
Output:
c a b
Time Complexity: The first step to create a graph takes O(n + alhpa) time where n is
number of given words and alpha is number of characters in given alphabet. The second
step is also topological sorting. Note that there would be alpha vertices and at-most (n-1)
edges in the graph. The time complexity of topological sorting is O(V+E) which is O(n +
aplha) here. So overall time complexity is O(n + aplha) + O(n + aplha) which is O(n +
aplha).
Exercise:
The above code doesn’t work when the input is not valid. For example {“aba”, “bba”,
“aaa”} is not valid, because from first two words, we can deduce ‘a’ should appear before ‘b’,
but from last two words, we can deduce ‘b’ should appear before ‘a’ which is not possible.
Extend the above program to handle invalid inputs and generate the output as “Not valid”.
This article is contributed by Piyush Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/
907
Chapter 126
Gnome Sort
• He looks at the flower pot next to him and the previous one; if they are in the right
order he steps one pot forward, otherwise he swaps them and steps one pot backwards.
• If there is no previous pot (he is at the starting of the pot line), he steps forwards; if
there is no pot next to him (he is at the end of the pot line), he is done.
Input –
Array- arr[]
Total elements - n
Algorithm Steps
1. If you are at the start of the array then go to the right element (from arr[0] to arr[1]).
2. If the current array element is larger or equal to the previous array element then go
one step right
3. If the current array element is smaller than the previous array element then swap these
two elements and go one step backwards
908
Chapter 126. Gnome Sort
4. Repeat steps 2) and 3) till ‘i’ reaches the end of the array (i.e- ‘n-1’)
5. If the end of the array is reached then stop and the array is sorted.
Example-
34 2 10 -9
909
Chapter 126. Gnome Sort
Java
910
Chapter 126. Gnome Sort
Python
911
Chapter 126. Gnome Sort
C#
912
Chapter 126. Gnome Sort
PHP
<?php
// PHP Program to implement
// Gnome Sort
// A function to sort the
// algorithm using gnome sort
function gnomeSort($arr, $n)
{
$index = 0;
while ($index < $n)
{
if ($index == 0)
$index++;
if ($arr[$index] >= $arr[$index - 1])
$index++;
else
{
$temp = 0;
$temp = $arr[$index];
$arr[$index] = $arr[$index - 1];
$arr[$index - 1] = $temp;
$index--;
}
}
echo "Sorted sequence ",
"after Gnome sort: ";
for ($i = 0; $i < $n; $i++)
echo $arr[$i] . " ";
echo "\n";
913
Chapter 126. Gnome Sort
}
// Driver Code
$arr = array(34, 2, 10, -9);
$n = count($arr);
gnomeSort($arr, $n);
// This code is contributed
// by Sam007
?>
Output:
Time Complexity – As there are no nested loop (only one while) it may seem that this
is a linear O(N) time algorithm. But the time complexity is O(N^2). This is because the
variable – ‘index’ in our program doesn’t always gets incremented, it gets decremented too.
However this sorting algorithm is adaptive and performs better if the array is already/partially
sorted.
Auxiliary Space – This is an in-place algorithm. So O(1) auxiliary space is needed.
Improved By : Sam007
Source
https://www.geeksforgeeks.org/gnome-sort-a-stupid-one/
914
Chapter 127
915
Chapter 127. Heap Sort for decreasing order using min heap
916
Chapter 127. Heap Sort for decreasing order using min heap
// Driver program
int main()
{
int arr[] = { 4, 6, 3, 2, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
cout << "Sorted array is \n";
printArray(arr, n);
}
Java
917
Chapter 127. Heap Sort for decreasing order using min heap
C#
918
Chapter 127. Heap Sort for decreasing order using min heap
// To heapify a subtree rooted with
// node i which is an index in arr[],
// n is size of heap
static void heapify(int[] arr, int n, int i)
{
int smallest = i; // Initialize smalles as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is smaller than root
if (l < n && arr[l] < arr[smallest])
smallest = l;
// If right child is smaller than smallest so far
if (r < n && arr[r] < arr[smallest])
smallest = r;
// If smallest is not root
if (smallest != i) {
int temp = arr[i];
arr[i] = arr[smallest];
arr[smallest] = temp;
// Recursively heapify the affected sub-tree
heapify(arr, n, smallest);
}
}
// main function to do heap sort
static void heapSort(int[] arr, int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
919
Chapter 127. Heap Sort for decreasing order using min heap
/* A utility function to print array of size n */
static void printArray(int[] arr, int n)
{
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver program
public static void Main()
{
int[] arr = { 4, 6, 3, 2, 9 };
int n = arr.Length;
heapSort(arr, n);
Console.WriteLine("Sorted array is ");
printArray(arr, n);
}
}
// This code is contributed by vt_m.
Output:
Sorted array is
9 6 4 3 2
Time complexity:It takes O(logn) for heapify and O(n) for constructing a heap.
Hence, the overall time complexity of heap sort using min heap or max heap is O(nlogn)
Source
https://www.geeksforgeeks.org/heap-sort-for-decreasing-order-using-min-heap/
920
Chapter 128
HeapSort
HeapSort - GeeksforGeeks
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It
is similar to selection sort where we first find the maximum element and place the maximum
element at the end. We repeat the same process for remaining element.
What is Binary Heap?
Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in which
every level, except possibly the last, is completely filled, and all nodes are as far left as
possible (Source Wikipedia)
A Binary Heap is a Complete Binary Tree where items are stored in a special order such that
value in a parent node is greater(or smaller) than the values in its two children nodes. The
former is called as max heap and the latter is called min heap. The heap can be represented
by binary tree or array.
Why array based representation for Binary Heap?
Since a Binary Heap is a Complete Binary Tree, it can be easily represented as array and
array based representation is space efficient. If the parent node is stored at index I, the left
child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing
starts at 0).
Heap Sort Algorithm for sorting in increasing order:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last
item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.
3. Repeat above steps while size of heap is greater than 1.
How to build the heap?
Heapify procedure can be applied to a node only if its children nodes are heapified. So the
heapification must be performed in the bottom up order.
Lets understand with the help of an example:
921
Chapter 128. HeapSort
C++
922
Chapter 128. HeapSort
// If largest is not root
if (largest != i)
{
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// main function to do heap sort
void heapSort(int arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
// Move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
for (int i=0; i<n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
// Driver program
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
cout << "Sorted array is \n";
printArray(arr, n);
}
923
Chapter 128. HeapSort
Java
924
Chapter 128. HeapSort
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = arr.length;
HeapSort ob = new HeapSort();
ob.sort(arr);
System.out.println("Sorted array is");
printArray(arr);
}
}
Python
925
Chapter 128. HeapSort
largest = r
# Change root, if needed
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
# Driver code to test above
arr = [ 12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" %arr[i]),
# This code is contributed by Mohit Kumra
C#
926
Chapter 128. HeapSort
{
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int[] arr, int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
/* A utility function to print array of size n */
static void printArray(int[] arr)
{
int n = arr.Length;
for (int i=0; i<n; ++i)
Console.Write(arr[i]+" ");
Console.Read();
}
927
Chapter 128. HeapSort
PHP
<?php
// Php program for implementation of Heap Sort
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
function heapify(&$arr, $n, $i)
{
$largest = $i; // Initialize largest as root
$l = 2*$i + 1; // left = 2*i + 1
$r = 2*$i + 2; // right = 2*i + 2
// If left child is larger than root
if ($l < $n && $arr[$l] > $arr[$largest])
$largest = $l;
// If right child is larger than largest so far
if ($r < $n && $arr[$r] > $arr[$largest])
$largest = $r;
// If largest is not root
if ($largest != $i)
{
$swap = $arr[$i];
$arr[$i] = $arr[$largest];
$arr[$largest] = $swap;
// Recursively heapify the affected sub-tree
heapify($arr, $n, $largest);
928
Chapter 128. HeapSort
}
}
// main function to do heap sort
function heapSort(&$arr, $n)
{
// Build heap (rearrange array)
for ($i = $n / 2 - 1; $i >= 0; $i--)
heapify($arr, $n, $i);
// One by one extract an element from heap
for ($i = $n-1; $i >= 0; $i--)
{
// Move current root to end
$temp = $arr[0];
$arr[0] = $arr[$i];
$arr[$i] = $temp;
// call max heapify on the reduced heap
heapify($arr, $i, 0);
}
}
/* A utility function to print array of size n */
function printArray(&$arr, $n)
{
for ($i = 0; $i < $n; ++$i)
echo ($arr[$i]." ") ;
}
// Driver program
$arr = array(12, 11, 13, 5, 6, 7);
$n = sizeof($arr)/sizeof($arr[0]);
heapSort($arr, $n);
echo 'Sorted array is ' . "\n";
printArray($arr , $n);
// This code is contributed by Shivi_Aggarwal
?>
Output:
Sorted array is
929
Chapter 128. HeapSort
5 6 7 11 12 13
Snapshots:
930
Chapter 128. HeapSort
931
Chapter 128. HeapSort
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.
Improved By : Shivi_Aggarwal, Abby_akku
Source
https://www.geeksforgeeks.org/heap-sort/
932
Chapter 129
933
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
934
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
}
// Driver program to test above functions
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Java
935
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
936
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
// Driver Code
static public void main (String[] args)
{
int []arr = {10, 7, 8, 9, 1, 5};
int n = arr.length;
quickSort(arr, 0, n-1);
System.out.println("Sorted array: ");
printArray(arr, n);
}
}
// This code is contributed by vt_m.
C#
// C# implementation QuickSort
// using Lomuto's partition Scheme
using System;
class GFG
{
static void Swap(int[] array,
int position1,
int position2)
{
// Swaps elements in an array
// Copy the first position's element
int temp = array[position1];
// Assign to the second element
array[position1] = array[position2];
// Assign to the first element
array[position2] = temp;
}
/* This function takes last element as
pivot, places the pivot element at its
correct position in sorted array, and
places all smaller (smaller than pivot)
to left of pivot and all greater elements
to right of pivot */
static int partition(int []arr, int low,
int high)
{
int pivot = arr[high];
937
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
938
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
// Driver Code
static public void Main()
{
int []arr = {10, 7, 8, 9, 1, 5};
int n = arr.Length;
quickSort(arr, 0, n-1);
Console.WriteLine("Sorted array: ");
printArray(arr, n);
}
}
// This code is contributed by vt_m.
Output:
Sorted array:
1 5 7 8 9 10
if i >= j then
return j
939
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
940
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
Java
941
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
942
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
}
/* Function to print an array */
static void printArray(int []arr, int n)
{
for (int i=0; i < n; i++)
System.out.print(" " + arr[i]);
System.out.println();
}
// Driver Code
static public void main (String[] args)
{
int []arr = {10, 7, 8, 9, 1, 5};
int n = arr.length;
quickSort(arr, 0, n - 1);
System.out.println("Sorted array: ");
printArray(arr, n);
}
}
// This code is contributed by vt_m.
C#
// C# implementation of QuickSort
// using Hoare's partition scheme
using System;
class GFG
{
/* This function takes last element
as pivot, places the pivot element
at its correct position in sorted
array, and places all smaller
(smaller than pivot) to left of pivot
and all greater elements to right
of pivot */
static int partition(int []arr, int low,
int high)
{
int pivot = arr[low];
int i = low - 1, j = high + 1;
while (true)
{
// Find leftmost element greater
943
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
944
Chapter 129. Hoare’s vs Lomuto partition scheme in QuickSort
Output:
Sorted array:
1 5 7 8 9 10
Comparison:
1. Hoare’s scheme is more efficient than Lomuto’s partition scheme because it does three
times fewer swaps on average, and it creates efficient partitions even when all values
are equal.
2. Like Lomuto’s partition scheme, Hoare partitioning also causes Quicksort to degrade
to O(n^2) when the input array is already sorted, it also doesn’t produce a stable sort.
3. Note that in this scheme, the pivot’s final location is not necessarily at the index that
was returned, and the next two segments that the main algorithm recurs on are (lo..p)
and (p+1..hi) as opposed to (lo..p-1) and (p+1..hi) as in Lomuto’s scheme.
Source : https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme
Improved By : vt_m
Source
https://www.geeksforgeeks.org/hoares-vs-lomuto-partition-scheme-quicksort/
945
Chapter 130
Input:
Date arr[] = {{20, 1, 2014},
{25, 3, 2010},
{ 3, 12, 2000},
{18, 11, 2001},
{19, 4, 2015},
{ 9, 7, 2005}}
Output:
Date arr[] = {{ 3, 12, 2000},
{18, 11, 2001},
{ 9, 7, 2005},
{25, 3, 2010},
{20, 1, 2014},
{19, 4, 2015}}
We strongly recommend to minimize your browser and try this yourself first.
A Simple Solution is to use a O(nLogn) algorithm like Merge Sort. We can sort the list in
O(n) time using Radix Sort. In a typical Radix Sort implementation, we first sort by last
digit, then by second last digit, and so on. Here we sort in following order.
1) First sort by day using counting sort
2) Then sort by month using counting sort
3) Finally sort by year using counting sort
946
Chapter 130. How to efficiently sort a big list dates in 20’s
As the number of days, months and years are fixed, all three steps take O(n) time. Therefore,
overall time complexity is O(n).
Below is C++ implementation of above idea. Note that the implementation doesn’t do any
error handing to keep the code simple.
// C++ program to sort an array of dates using Radix Sort
#include <bits/stdc++.h>
struct Date
{
int d, m, y;
};
// Prototypes
void countSortDay(Date arr[], int n);
void countSortMonth(Date arr[], int n);
void countSortYear(Date arr[], int n);
// The main function that sorts array of dates
// using Radix Sort
void radixSortDates(Date arr[], int n)
{
// First sort by day
countSortDay(arr, n);
// Then by month
countSortMonth(arr, n);
// Finally by year
countSortYear(arr, n);
}
// A function to do counting sort of arr[] according to
// day
void countSortDay(Date arr[], int n)
{
Date output[n]; // output array
int i, count[31] = {0};
// Store count of occurrences in count[]
for (i=0; i<n; i++)
count[arr[i].d – 1]++;
// Change count[i] so that count[i] now contains
// actual position of this day in output[]
for (i=1; i<31; i++)
count[i] += count[i-1];
// Build the output array
for (i=n-1; i>=0; i–)
{
output[count[arr[i].d – 1] – 1] = arr[i];
count[arr[i].d – 1]–;
}
947
Chapter 130. How to efficiently sort a big list dates in 20’s
948
Chapter 130. How to efficiently sort a big list dates in 20’s
Input Dates
{20, 1, 2014}
{25, 3, 2010}
{ 3, 12, 2000}
{18, 11, 2001}
{19, 4, 2015}
{ 9, 7, 2005}
Sorted Dates
{ 3, 12, 2000}
{18, 11, 2001}
{ 9, 7, 2005}
{25, 3, 2010}
{20, 1, 2014}
{19, 4, 2015}
This article is contributed by Rajeev. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/how-to-efficiently-sort-a-big-list-dates-in-20s/
949
Chapter 131
Input : 1 2 3 4
Subarrays with size of 1:|1||2| |3||4|
Subarrays with size of 2: |1 2| |3 4|
Output : 1 2 3 4
Input : 1 2 3 4 5 6 7 8
Subarrays with size of 1: |1||2| |3||4| |5||6| |7||8|
Subarrays with size of 2: |1 2| |3 4| |5 6| |7 8|
Subarrays with size of 4: |1 2 3 4| |5 6 7 8|
Output : 1 2 3 4 5 6 7 8
950
Chapter 131. How to make Mergesort to perform O(n) comparisons in best case?
951
Chapter 131. How to make Mergesort to perform O(n) comparisons in best case?
Output:
1 2 3 4 5 6 7 8
Source
https://www.geeksforgeeks.org/make-mergesort-perform-comparisons-best-case/
952
Chapter 132
Example:
Input: arr[] = {100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1}
Output: arr[] = {1, 1, 1, 1, 1, 12, 12, 12, 100, 100, 100, 100}
We strongly recommend you to minimize your browser and try this yourself
first.
A Basic Sorting algorithm like MergeSort, HeapSortwould take O(nLogn) time where n is
number of elements, can we do better?
A Better Solution is to use Self-Balancing Binary Search Tree like AVLor Red-Black to
sort in O(n Log m) time where m is number of distinct elements. The idea is to extend tree
node to have count of keys also.
struct Node
{
int key;
struct Node *left. *right;
int count; // Added to handle duplicates
953
Chapter 132. How to sort a big array with many repetitions?
954
Chapter 132. How to sort a big array with many repetitions?
955
Chapter 132. How to sort a big array with many repetitions?
956
Chapter 132. How to sort a big array with many repetitions?
957
Chapter 132. How to sort a big array with many repetitions?
Output:
Input array is
100, 12, 100, 1, 1, 12, 100, 1, 12, 100, 1, 1,
Sorted array is
1, 1, 1, 1, 1, 12, 12, 12, 100, 100, 100, 100,
958
Chapter 132. How to sort a big array with many repetitions?
Output:
959
Chapter 132. How to sort a big array with many repetitions?
Input array is
100 12 100 1 1 12 100 1 12 100 1 1
Sorted array is
1 1 1 1 1 12 12 12 100 100 100 100
This article is contributed by Ankur. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/how-to-sort-a-big-array-with-many-repetitions/
960
Chapter 133
Input:
Date arr[] = {{20, 1, 2014},
{25, 3, 2010},
{ 3, 12, 1676},
{18, 11, 1982},
{19, 4, 2015},
{ 9, 7, 2015}}
Output:
Date arr[] = {{ 3, 12, 1676},
{18, 11, 1982},
{25, 3, 2010},
{20, 1, 2014},
{19, 4, 2015},
{ 9, 7, 2015}}
We strongly recommend you to minimize your browser and try this yourself
first
The idea is to use in-built function to sort function in C++. We can write our own compare
function that first compares years, then months, then days.
Below is complete C++ program.
961
Chapter 133. How to sort an array of dates in C/C++?
962
Chapter 133. How to sort an array of dates in C/C++?
{25, 3, 2010},
{ 3, 12, 1676},
{18, 11, 1982},
{19, 4, 2015},
{ 9, 7, 2015}};
int n = sizeof(arr)/sizeof(arr[0]);
sortDates(arr, n);
cout << "Sorted dates are\n";
for (int i=0; i<n; i++)
{
cout << arr[i].day << " " << arr[i].month
<< " " << arr[i].year;
cout << endl;
}
}
Output:
Source
https://www.geeksforgeeks.org/how-to-sort-an-array-of-dates-in-cc/
963
Chapter 134
In-Place Algorithm
An in-place algorithm is an algorithm that does not need an extra space and
produces an output in the same memory that contains the data by transforming
the input ‘in-place’. However, a small constant extra space used for variables is
allowed.
In-place means that the algorithm does not use extra space for manipulating the
input but may require a small though nonconstant extra space for its operation.
Usually, this space is O(log n), though sometimes anything in o(n) (Smaller than
linear) is allowed [Source : Wikipedia]
964
Chapter 134. In-Place Algorithm
// Now copy reversed elements back to arr[]
for (int i=0; i<n; i++)
arr[i] = rev[i];
}
/* Utility function to print an array */
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
/* Driver function to test above functions */
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
printArray(arr, n);
revereseArray(arr, n);
cout << "Reversed array is" << endl;
printArray(arr, n);
return 0;
}
Java
965
Chapter 134. In-Place Algorithm
Python3
966
Chapter 134. In-Place Algorithm
arr[i] = rev[i]
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6]
n = len(arr)
print(*arr)
revereseArray(arr, n);
print("Reversed array is")
print(*arr)
# This code is contributed
# by Harshit Saini
Output:
1 2 3 4 5 6
Reversed array is
6 5 4 3 2 1
967
Chapter 134. In-Place Algorithm
968
Chapter 134. In-Place Algorithm
printArray(arr, n);
return 0;
}
Java
969
Chapter 134. In-Place Algorithm
Python3
Output:
1 2 3 4 5 6
Reversed array is
6 5 4 3 2 1
970
Chapter 134. In-Place Algorithm
This needs O(1) extra space for exchanging elements and is an example of in-place algorithm.
Which Sorting Algorithms are In-Place and which are not?
In Place : Bubble sort, Selection Sort, Insertion Sort, Heapsort.
Not In-Place : Merge Sort. Note that merge sort requires O(n) extra space.
What about QuickSort? Why is it called In-Place?
QuickSort uses extra space for recursive function calls. It is called in-place according to broad
definition as extra space required is not used to manipulate input, but only for recursive
calls.
Improved By : Harshit Saini
Source
https://www.geeksforgeeks.org/in-place-algorithm/
971
Chapter 135
Insertion Sort
972
Chapter 135. Insertion Sort
Another Example:
12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 5 (Size of input array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6
i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13
11, 12, 13, 5, 6
i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one
position ahead of their current position.
5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position
ahead of their current position.
5, 6, 11, 12, 13
C/C++
973
Chapter 135. Insertion Sort
Java
974
Chapter 135. Insertion Sort
{
/*Function to sort array using insertion sort*/
void sort(int arr[])
{
int n = arr.length;
for (int i=1; i<n; ++i)
{
int key = arr[i];
int j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j>=0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
/* A utility function to print array of size n*/
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6};
InsertionSort ob = new InsertionSort();
ob.sort(arr);
printArray(arr);
}
} /* This code is contributed by Rajat Mishra. */
Python
975
Chapter 135. Insertion Sort
C#
976
Chapter 135. Insertion Sort
PHP
<?php
// PHP program for insertion sort
// Function to sort an array
// using insertion sort
function insertionSort(&$arr, $n)
{
for ($i = 1; $i < $n; $i++)
{
$key = $arr[$i];
$j = $i-1;
// Move elements of arr[0..i-1],
// that are greater than key, to
977
Chapter 135. Insertion Sort
Output:
5 6 11 12 13
978
Chapter 135. Insertion Sort
Snapshots:
979
Chapter 135. Insertion Sort
980
Chapter 135. Insertion Sort
Source
https://www.geeksforgeeks.org/insertion-sort/
981
Chapter 136
function insertionSort(V)
i, j, k
for i from 1..length(V)
k = V[i]
j = i-1
while j > 0 and k < V[j]
V[j+1] = V[j]
j -= 1
V[j] = k
return V
Inside the while loop, we shift all values larger than k by one position and then insert k into
the first position where k is larger than the array value. The same effect is obtained if we
swap consecutive array elements. By repeated swapping k will travel to its correct position.
Let’s take an example to illustrate this
Insert 3 in A = {1, 2, 4, 5, 6}
982
Chapter 136. Insertion Sort by Swapping Elements
function insertionSort(V)
for i in 1...length(V)
j = i
while ( j > 0 and V[j] < V[j-1])
Swap V[j] and V[j-1]
j -= 1
return V
983
Chapter 136. Insertion Sort by Swapping Elements
int i, j, key;
for (i = 1; i < N; i++) {
j = i;
// Insert V[i] into list 0..i-1
while (j > 0 and V[j] < V[j - 1]) {
// Swap V[j] and V[j-1]
swap(V[j], V[j - 1]);
// Decrement j by 1
j -= 1;
}
}
}
// Driver Code
int main()
{
Vector A = { 9, 8, 7, 5, 2, 1, 2, 3 };
cout << "Array: " << endl;
printVector(A);
cout << "After Sorting :" << endl;
insertionSort(A);
printVector(A);
return 0;
}
Java
984
Chapter 136. Insertion Sort by Swapping Elements
System.out.println();
}
// Function performs insertion sort on
// vector V
static void insertionSort(Vector<Integer> V)
{
int N = V.size();
int i, j, key;
for (i = 1; i < N; i++) {
j = i;
// Insert V[i] into list 0..i-1
while (j > 0 && V.get(j) < V.get(j - 1)) {
// Swap V[j] and V[j-1]
int temp= V.get(j);
V.set(j, V.get(j - 1));
V.set(j - 1, temp);
// Decrement j by 1
j -= 1;
}
}
}
public static void main (String[] args)
{
Vector<Integer> A = new Vector<Integer> ();
A.add(0, 9);
A.add(1, 8);
A.add(2, 7);
A.add(3, 5);
A.add(4, 2);
A.add(5, 1);
A.add(6, 2);
A.add(7, 3);
System.out.print("Array: ");
printVector(A);
System.out.print("After Sorting :");
insertionSort(A);
printVector(A);
}
}
//This code is contributed by Gitanjali.
985
Chapter 136. Insertion Sort by Swapping Elements
Python3
Output:
Array:
986
Chapter 136. Insertion Sort by Swapping Elements
9 8 7 5 2 1 2 3
After Sorting :
1 2 2 3 5 7 8 9
function insertionSortRecursive(A, N)
if N >= 1
insertionSortRecursive(A, N-1)
j = N-1
while j > 0 and A[j] < A[j-1]
Swap A[j] and A[j-1]
j = j-1
[end of while]
[end of if]
987
Chapter 136. Insertion Sort by Swapping Elements
Java
988
Chapter 136. Insertion Sort by Swapping Elements
989
Chapter 136. Insertion Sort by Swapping Elements
A.add(4, 2);
A.add(5, 1);
A.add(6, 2);
A.add(7, 3);
System.out.print("Array: ");
printVector(A);
System.out.print("After Sorting :");
insertionSortRecursive(A,A.size());
printVector(A);
}
}
// This code is contributed by Gitanjali.
Python3
990
Chapter 136. Insertion Sort by Swapping Elements
temp = V[j];
V[j] = V[j - 1];
V[j-1] = temp;
# Decrement j
j -= 1
# Driver method
A = [ 9, 8, 7, 5, 2, 1, 2, 3 ]
n=len(A)
print("Array")
printVector(A)
print( "After Sorting :")
insertionSortRecursive(A,n)
printVector(A)
# This code is contributed
# by Gitanjali.
Output
Array:
9 8 7 5 2 1 2 3
After Sorting :
1 2 2 3 5 7 8 9
Note
The Time Complexity of the algorithm is still O(N^2) in the worst case. Moreover, these
versions are potentially slower since repeated swapping requires more operations. However,
these versions are discussed because of their implementation simplicity and ease of under-
standing.
References
Stack Overflow – Insertion Sort by Swapping
Source
https://www.geeksforgeeks.org/insertion-sort-swapping-elements/
991
Chapter 137
Algorithm:
Below is a simple insertion sort algorithm for doubly linked list.
1) Create an empty sorted (or result) doubly linked list.
2) Traverse the given doubly linked list, do following for every node.
……a) Insert current node in sorted way in sorted(or result) doubly linked list.
3) Change head of given linked list to head of sorted (or result) list.
The main step is (2.a) which has been covered in below post.
Sorted Insert for Doubly Linked List
992
Chapter 137. Insertion Sort for Doubly Linked List
993
Chapter 137. Insertion Sort for Doubly Linked List
/*Make the appropriate links */
newNode->next = current->next;
// if the new node is not inserted
// at the end of the list
if (current->next != NULL)
newNode->next->prev = newNode;
current->next = newNode;
newNode->prev = current;
}
}
// function to sort a doubly linked list using insertion sort
void insertionSort(struct Node** head_ref)
{
// Initialize 'sorted' - a sorted doubly linked list
struct Node* sorted = NULL;
// Traverse the given doubly linked list and
// insert every node to 'sorted'
struct Node* current = *head_ref;
while (current != NULL) {
// Store next for next iteration
struct Node* next = current->next;
// removing all the links so as to create 'current'
// as a new node for insertion
current->prev = current->next = NULL;
// insert current in 'sorted' doubly linked list
sortedInsert(&sorted, current);
// Update current
current = next;
}
// Update head_ref to point to sorted doubly linked list
*head_ref = sorted;
}
// function to print the doubly linked list
void printList(struct Node* head)
{
while (head != NULL) {
994
Chapter 137. Insertion Sort for Doubly Linked List
995
Chapter 137. Insertion Sort for Doubly Linked List
printList(head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/insertion-sort-doubly-linked-list/
996
Chapter 138
Insertion sort to sort even and odd positioned elements in different orders - GeeksforGeeks
We are given an array. We need to sort the even positioned elements in the ascending order
and the odd positioned elements in the descending order. We must apply insertion sort to
sort them.
Examples:
We separately apply the insertion sort technique on the even positioned elements and the
odd positioned elements separately but within the same array. The loop starts for the odd
positioned from the 0th index(1st element) and the for the even from the 1st index(2nd
element) and keep on increasing by 2 since every alternate is odd/even positioned.
We now simply apply the insertion sort procedure on the odd positioned and even positioned.
the odd positioned elements are A[0, 2, 4, …] and even are A[1, 3, 5, 7..]. So they are
considered as separate sub-arrays but within the same array.
Explanation for the odd positioned:
The 0th element already sorted. Now the 2nd element compared with the 0th and inserted
and so on the (i+2)th element compared with the previous ones until the end of the array.
997
Chapter 138. Insertion sort to sort even and odd positioned elements in different orders
998
Chapter 138. Insertion sort to sort even and odd positioned elements in different orders
}
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
evenOddInsertionSort(arr, n);
printArray(arr, n);
return 0;
}
Python3
999
Chapter 138. Insertion sort to sort even and odd positioned elements in different orders
Output:13 5 12 11 6
There exist better approaches to solve this problem without insertion sort. Please refer Sort
even-placed elements in increasing and odd-placed in decreasing orderfor details.
1000
Chapter 138. Insertion sort to sort even and odd positioned elements in different orders
Source
https://www.geeksforgeeks.org/insertion-sorteven-odd-positioned-elements/
1001
Chapter 139
1002
Chapter 139. Insertion sort using C++ STL
Output:
1 2 3 4 5 5 6 7
Source
https://www.geeksforgeeks.org/insertion-sort-using-c-stl/
1003
Chapter 140
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data);
/*This solution uses the temporary dummy to build up the result list */
struct Node* sortedIntersect(struct Node* a, struct Node* b)
1004
Chapter 140. Intersection of two Sorted Linked Lists
{
struct Node dummy;
struct Node* tail = &dummy;
dummy.next = NULL;
/* Once one or the other list runs out -- we're done */
while (a != NULL && b != NULL)
{
if (a->data == b->data)
{
push((&tail->next), a->data);
tail = tail->next;
a = a->next;
b = b->next;
}
else if (a->data < b->data) /* advance the smaller list */
a = a->next;
else
b = b->next;
}
return(dummy.next);
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
1005
Chapter 140. Intersection of two Sorted Linked Lists
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty lists */
struct Node* a = NULL;
struct Node* b = NULL;
struct Node *intersect = NULL;
/* Let us create the first sorted linked list to test the functions
Created linked list will be 1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
/* Let us create the second sorted linked list
Created linked list will be 2->4->6->8 */
push(&b, 8);
push(&b, 6);
push(&b, 4);
push(&b, 2);
/* Find the intersection two linked lists */
intersect = sortedIntersect(a, b);
printf("\n Linked list containing common items of a & b \n ");
printList(intersect);
getchar();
}
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked
lists respectively.
Method 2 (Using Local References)
This solution is structurally very similar to the above, but it avoids using a dummy node
Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last
pointer of the result list. This solves the same case that the dummy node did — dealing
with the result list when it is empty. If you are trying to build up a list at its tail, either
the dummy node or the struct node** “reference” strategy can be used
#include<stdio.h>
#include<stdlib.h>
1006
Chapter 140. Intersection of two Sorted Linked Lists
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data);
/* This solution uses the local reference */
struct Node* sortedIntersect(struct Node* a, struct Node* b)
{
struct Node* result = NULL;
struct Node** lastPtrRef = &result;
/* Advance comparing the first nodes in both lists.
When one or the other list runs out, we're done. */
while (a!=NULL && b!=NULL)
{
if (a->data == b->data)
{
/* found a node for the intersection */
push(lastPtrRef, a->data);
lastPtrRef = &((*lastPtrRef)->next);
a = a->next;
b = b->next;
}
else if (a->data < b->data)
a=a->next; /* advance the smaller list */
else
b=b->next;
}
return(result);
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
1007
Chapter 140. Intersection of two Sorted Linked Lists
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while(node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty lists */
struct Node* a = NULL;
struct Node* b = NULL;
struct Node *intersect = NULL;
/* Let us create the first sorted linked list to test the functions
Created linked list will be 1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
/* Let us create the second sorted linked list
Created linked list will be 2->4->6->8 */
push(&b, 8);
push(&b, 6);
push(&b, 4);
push(&b, 2);
/* Find the intersection two linked lists */
intersect = sortedIntersect(a, b);
printf("\n Linked list containing common items of a & b \n ");
printList(intersect);
getchar();
}
1008
Chapter 140. Intersection of two Sorted Linked Lists
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked
lists respectively.
Method 3 (Recursive)
Below is the recursive implementation of sortedIntersect().
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
struct Node *sortedIntersect(struct Node *a, struct Node *b)
{
/* base case */
if (a == NULL || b == NULL)
return NULL;
/* If both lists are non-empty */
/* advance the smaller list and call recursively */
if (a->data < b->data)
return sortedIntersect(a->next, b);
if (a->data > b->data)
return sortedIntersect(a, b->next);
// Below lines are executed only when a->data == b->data
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = a->data;
/* advance both lists and call recursively */
temp->next = sortedIntersect(a->next, b->next);
return temp;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
1009
Chapter 140. Intersection of two Sorted Linked Lists
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty lists */
struct Node* a = NULL;
struct Node* b = NULL;
struct Node *intersect = NULL;
/* Let us create the first sorted linked list to test the functions
Created linked list will be 1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
/* Let us create the second sorted linked list
Created linked list will be 2->4->6->8 */
push(&b, 8);
push(&b, 6);
push(&b, 4);
push(&b, 2);
/* Find the intersection two linked lists */
intersect = sortedIntersect(a, b);
printf("\n Linked list containing common items of a & b \n ");
printList(intersect);
1010
Chapter 140. Intersection of two Sorted Linked Lists
return 0;
}
Time Complexity: O(m+n) where m and n are number of nodes in first and second linked
lists respectively.
References:
cslibrary.stanford.edu/105/LinkedListProblems.pdf
Source
https://www.geeksforgeeks.org/intersection-of-two-sorted-linked-lists/
1011
Chapter 141
Iterative HeapSort
Input : 10 20 15 17 9 21
Output : 9 10 15 17 20 21
Input: 12 11 13 5 6 7 15 5 19
Output: 5 5 6 7 11 12 13 15 19
1012
Chapter 141. Iterative HeapSort
15 10 9 17 20 21
10 9 15 17 20 21
9 10 15 17 20 21
Here, underlined part is sorted part.
1013
Chapter 141. Iterative HeapSort
{
index = (2 * j + 1);
// if left child is smaller than
// right child point index variable
// to right child
if (arr[index] < arr[index + 1] &&
index < (i - 1))
index++;
// if parent is smaller than child
// then swapping parent with child
// having higher value
if (arr[j] < arr[index] && index < i)
swap(arr[j], arr[index]);
j = index;
} while (index < i);
}
}
// Driver Code to test above
int main()
{
int arr[] = {10, 20, 15, 17, 9, 21};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Given array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n\n");
heapSort(arr, n);
// print array after sorting
printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output :
Given array: 10 20 15 17 9 21
1014
Chapter 141. Iterative HeapSort
Sorted array: 9 10 15 17 20 21
Here, both function buildMaxHeap and heapSort runs in O(nlogn) time. So, overall time
complexity is O(nlogn)
Source
https://www.geeksforgeeks.org/iterative-heap-sort/
1015
Chapter 142
1016
Chapter 142. Iterative Merge Sort
1017
Chapter 142. Iterative Merge Sort
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
Java
1018
Chapter 142. Iterative Merge Sort
1019
Chapter 142. Iterative Merge Sort
Python
1020
Chapter 142. Iterative Merge Sort
C#
1021
Chapter 142. Iterative Merge Sort
1022
Chapter 142. Iterative Merge Sort
/* Function to print an array */
static void printArray(int []A, int size)
{
int i;
for (i=0; i < size; i++)
Console.Write(A[i]+" ");
Console.Write("\n");
}
/* Driver program to test above functions */
public static void Main()
{
int []arr = {12, 11, 13, 5, 6, 7};
int arr_size = arr.Length;
Console.Write("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
Console.Write("\nSorted array is \n");
printArray(arr, arr_size);
}
}
// This code is contributed by Smitha
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
1023
Chapter 142. Iterative Merge Sort
#include<stdlib.h>
#include<stdio.h>
/* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */
void merge(int arr[], int l, int m, int r);
// Utility function to find minimum of two integers
int min(int x, int y) { return (x<y)? x :y; }
/* Iterative mergesort function to sort arr[0...n-1] */
void mergeSort(int arr[], int n)
{
int curr_size; // For current size of subarrays to be merged
// curr_size varies from 1 to n/2
int left_start; // For picking starting index of left subarray
// to be merged
// Merge subarrays in bottom up manner. First merge subarrays of
// size 1 to create sorted subarrays of size 2, then merge subarrays
// of size 2 to create sorted subarrays of size 4, and so on.
for (curr_size=1; curr_size<=n-1; curr_size = 2*curr_size)
{
// Pick starting point of different subarrays of current size
for (left_start=0; left_start<n-1; left_start += 2*curr_size)
{
// Find ending point of left subarray. mid+1 is starting
// point of right
int mid = left_start + curr_size - 1;
int right_end = min(left_start + 2*curr_size - 1, n-1);
// Merge Subarrays arr[left_start...mid] & arr[mid+1...right_end]
merge(arr, left_start, mid, right_end);
}
}
}
/* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
1024
Chapter 142. Iterative Merge Sort
1025
Chapter 142. Iterative Merge Sort
printf("\n");
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, n);
mergeSort(arr, n);
printf("\nSorted array is \n");
printArray(arr, n);
return 0;
}
Java
1026
Chapter 142. Iterative Merge Sort
1027
Chapter 142. Iterative Merge Sort
1028
Chapter 142. Iterative Merge Sort
System.out.printf("Given array is \n");
printArray(arr, n);
mergeSort(arr, n);
System.out.printf("\nSorted array is \n");
printArray(arr, n);
}
}
// This code is contributed by Smitha
Python 3
1029
Chapter 142. Iterative Merge Sort
1030
Chapter 142. Iterative Merge Sort
# Contributed by Madhur Chhangani [RCOEM]
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Source
https://www.geeksforgeeks.org/iterative-merge-sort/
1031
Chapter 143
1032
Chapter 143. Iterative Quick Sort
i++;
swap (&arr[i], &arr[j]);
}
}
swap (&arr[i + 1], &arr[h]);
return (i + 1);
}
/* A[] --> Array to be sorted,
l --> Starting index,
h --> Ending index */
void quickSort(int A[], int l, int h)
{
if (l < h)
{
/* Partitioning index */
int p = partition(A, l, h);
quickSort(A, l, p - 1);
quickSort(A, p + 1, h);
}
}
// Driver code
int main(){
int n = 5;
int arr[n] = {4, 2, 6, 9, 2};
quickSort(arr, 0, n-1);
for(int i = 0; i < n; i++){
cout << arr[i] << " ";
}
return 0;
}
Java
1033
Chapter 143. Iterative Quick Sort
1034
Chapter 143. Iterative Quick Sort
// Driver code
public static void main(String args[])
{
int n = 5;
int arr[] = {4, 2, 6, 9, 2};
qSort(arr, 0, n-1);
for(int i =0;i<n;i++){
System.out.print(arr[i]+" ");
}
}
}
Python3
1035
Chapter 143. Iterative Quick Sort
C#
1036
Chapter 143. Iterative Quick Sort
// index of smaller element
int i = (low-1);
for (int j = low; j <= high-1; j++)
{
// If current element is
// smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high]
// (or pivot)
temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
/* The main function that implements
QuickSort() arr[] --> Array to be
sorted,
low --> Starting index,
high --> Ending index */
static void qSort(int []arr, int low,
int high)
{
if (low < high)
{
/* pi is partitioning index,
arr[pi] is now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements
// before partition and after
// partition
qSort(arr, low, pi-1);
qSort(arr, pi+1, high);
1037
Chapter 143. Iterative Quick Sort
}
}
// Driver code
public static void Main()
{
int n = 5;
int []arr = {4, 2, 6, 9, 2};
qSort(arr, 0, n-1);
for(int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by nitin mittal.
Output:
2 2 4 6 9
1038
Chapter 143. Iterative Quick Sort
#include <stdio.h>
// A utility function to swap two elements
void swap ( int* a, int* b )
{
int t = *a;
*a = *b;
*b = t;
}
/* This function is same in both iterative and recursive*/
int partition (int arr[], int l, int h)
{
int x = arr[h];
int i = (l - 1);
for (int j = l; j <= h- 1; j++)
{
if (arr[j] <= x)
{
i++;
swap (&arr[i], &arr[j]);
}
}
swap (&arr[i + 1], &arr[h]);
return (i + 1);
}
/* A[] --> Array to be sorted,
l --> Starting index,
h --> Ending index */
void quickSortIterative (int arr[], int l, int h)
{
// Create an auxiliary stack
int stack[ h - l + 1 ];
// initialize top of stack
int top = -1;
// push initial values of l and h to stack
stack[ ++top ] = l;
stack[ ++top ] = h;
// Keep popping from stack while is not empty
while ( top >= 0 )
{
// Pop h and l
h = stack[ top-- ];
1039
Chapter 143. Iterative Quick Sort
Java
1040
Chapter 143. Iterative Quick Sort
{
/* This function takes last element as pivot,
places the pivot element at its correct
position in sorted array, and places all
smaller (smaller than pivot) to left of
pivot and all greater elements to right
of pivot */
static int partition(int arr[], int low, int high)
{
int pivot = arr[high];
// index of smaller element
int i = (low-1);
for (int j = low; j <= high-1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
/* A[] --> Array to be sorted,
l --> Starting index,
h --> Ending index */
static void quickSortIterative (int arr[], int l, int h)
{
// Create an auxiliary stack
int[] stack = new int[h-l+1];
// initialize top of stack
int top = -1;
// push initial values of l and h to stack
1041
Chapter 143. Iterative Quick Sort
stack[++top] = l;
stack[++top] = h;
// Keep popping from stack while is not empty
while (top >= 0)
{
// Pop h and l
h = stack[top--];
l = stack[top--];
// Set pivot element at its correct position
// in sorted array
int p = partition(arr, l, h);
// If there are elements on left side of pivot,
// then push left side to stack
if (p-1 > l)
{
stack[++top] = l;
stack[++top] = p - 1;
}
// If there are elements on right side of pivot,
// then push right side to stack
if (p+1 < h)
{
stack[++top] = p + 1;
stack[++top] = h;
}
}
}
// Driver code
public static void main(String args[])
{
int arr[] = {4, 3, 5, 2, 1, 3, 2, 3};
int n = 8;
// Function calling
quickSortIterative(arr, 0, n-1);
for(int i = 0; i < n; i++){
System.out.print(arr[i] + " ");
}
}
}
Python
1042
Chapter 143. Iterative Quick Sort
1043
Chapter 143. Iterative Quick Sort
# If there are elements on left side of pivot,
# then push left side to stack
if p-1 > l:
top = top + 1
stack[top] = l
top = top + 1
stack[top] = p - 1
# If there are elements on right side of pivot,
# then push right side to stack
if p+1 < h:
top = top + 1
stack[top] = p + 1
top = top + 1
stack[top] = h
# Driver code to test above
arr = [4, 3, 5, 2, 1, 3, 2, 3]
n = len(arr)
quickSortIterative(arr, 0, n-1)
print ("Sorted array is:")
for i in range(n):
print ("%d" %arr[i]),
# This code is contributed by Mohit Kumra
C#
1044
Chapter 143. Iterative Quick Sort
1045
Chapter 143. Iterative Quick Sort
l = stack[top--];
// Set pivot element at its
// correct position in
// sorted array
int p = partition(arr, l, h);
// If there are elements on
// left side of pivot, then
// push left side to stack
if (p-1 > l)
{
stack[++top] = l;
stack[++top] = p - 1;
}
// If there are elements on
// right side of pivot, then
// push right side to stack
if (p+1 < h)
{
stack[++top] = p + 1;
stack[++top] = h;
}
}
}
// Driver code
public static void Main()
{
int []arr = {4, 3, 5, 2, 1, 3, 2, 3};
int n = 8;
// Function calling
quickSortIterative(arr, 0, n-1);
for(int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by anuj_67.
Output:
1 2 2 3 3 3 4 5
The above mentioned optimizations for recursive quick sort can also be applied to iterative
1046
Chapter 143. Iterative Quick Sort
version.
1) Partition process is same in both recursive and iterative. The same techniques to choose
optimal pivot can also be applied to iterative version.
2) To reduce the stack size, first push the indexes of smaller half.
3) Use insertion sort when the size reduces below a experimentally calculated threshold.
References:
http://en.wikipedia.org/wiki/Quicksort
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.
Improved By : nitin mittal, vt_m
Source
https://www.geeksforgeeks.org/iterative-quick-sort/
1047
Chapter 144
Syntax :
Advantage :
parallelSort() method uses concept of MultiThreading which makes the sorting faster as
compared to normal sorting method.
1048
Chapter 144. Java 8 Arrays parallelSort() method with Examples
Example
Below are the program that will illustrate the use of Arrays.parallelSort():
Program 1: To demonstrate use of Parallel Sort
1049
Chapter 144. Java 8 Arrays parallelSort() method with Examples
Output:
Unsorted Array: 9 8 7 6 3 1
Sorted Array: 1 3 6 7 8 9
1050
Chapter 144. Java 8 Arrays parallelSort() method with Examples
Output:
1051
Chapter 144. Java 8 Arrays parallelSort() method with Examples
.
For iteration number: 99
Start and End Time in Serial (in ns): 3951050723541:3951050731520
Time taken by Serial Sort(in ns): 7979
Start and End Time in parallel (in ns): 3951050754238:3951050756130
Time taken by Parallel Sort(in ns): 1892
Note : Different time intervals will be printed But parallel sort will be done before normal
sort.
Environment: 2.6 GHz Intel Core i7, java version 8
Source
https://www.geeksforgeeks.org/java-8-arrays-parallelsort-method-with-examples/
1052
Chapter 145
Source
https://www.geeksforgeeks.org/java-program-for-binary-insertion-sort/
Java
1053
Chapter 145. Java Program for Binary Insertion Sort
}
public void sort(int array[])
{
for (int i = 1; i < array.length; i++)
{
int x = array[i];
// Find location to insert using binary search
int j = Math.abs(Arrays.binarySearch(array, 0, i, x) + 1);
//Shifting array to one location right
System.arraycopy(array, j, array, j+1, i-j);
//Placing element at its correct location
array[j] = x;
}
}
}
// Code contributed by Mohit Gupta_OMG
Please refer complete article on Binary Insertion Sort for more details!
1054
Chapter 146
Source
https://www.geeksforgeeks.org/java-program-for-bubble-sort/
Java
1055
Chapter 146. Java Program for Bubble Sort
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method to test above
public static void main(String args[])
{
BubbleSort ob = new BubbleSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
ob.bubbleSort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
/* This code is contributed by Rajat Mishra */
1056
Chapter 147
• It is based on the idea that array to be sorted can be divided into cycles. Cycles can
be visualized as a graph. We have n nodes and an edge directed from node i to node
j if the element at i-th index must be present at j-th index in the sorted array.
Cycle in arr[] = {4, 5, 2, 1, 5}
1057
Chapter 147. Java Program for Cycle Sort
We one by one consider all cycles. We first consider the cycle that includes first element.
We find correct position of first element, place it at its correct position, say j. We consider
old value of arr[j] and find its correct position, we keep doing this till all elements of
current cycle are placed at correct position, i.e., we don\’t come back to cycle starting point.
Source
https://www.geeksforgeeks.org/java-program-for-cycle-sort/
Java
1058
Chapter 147. Java Program for Cycle Sort
// Find position where we put the item. We basically
// count all smaller elements on right side of item.
int pos = cycle_start;
for (int i = cycle_start+1; i<n; i++)
if (arr[i] < item)
pos++;
// If item is already in correct position
if (pos == cycle_start)
continue;
// ignore all duplicate elements
while (item == arr[pos])
pos += 1;
// put the item to it\'s right position
if (pos != cycle_start)
{
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}
// Rotate rest of the cycle
while (pos != cycle_start)
{
pos = cycle_start;
// Find position where we put the element
for (int i = cycle_start+1; i<n; i++)
if (arr[i] < item)
pos += 1;
// ignore all duplicate elements
while (item == arr[pos])
pos += 1;
// put the item to it\'s right position
if (item != arr[pos])
{
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}
}
1059
Chapter 147. Java Program for Cycle Sort
}
}
// Driver program to test above function
public static void main(String[] args)
{
int arr[] = {1, 8, 3, 9, 10, 10, 2, 4 };
int n = arr.length;
cycleSort(arr, n) ;
System.out.println("After sort : ");
for (int i =0; i<n; i++)
System.out.print(arr[i] + " ");
}
}
// Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:
After sort :
1 2 3 4 8 9 10 10
1060
Chapter 148
Source
https://www.geeksforgeeks.org/java-program-for-heap-sort/
Java
1061
Chapter 148. Java Program for Heap Sort
1062
Chapter 148. Java Program for Heap Sort
1063
Chapter 149
Source
https://www.geeksforgeeks.org/java-program-for-iterative-merge-sort/
Java
1064
Chapter 149. Java Program for Iterative Merge Sort
1065
Chapter 149. Java Program for Iterative Merge Sort
Please refer complete article on Iterative Merge Sort for more details!
1066
Chapter 150
The key process in quickSort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x.
All this should be done in linear time.
Pseudo Code for recursive QuickSort function :
1067
Chapter 150. Java Program for QuickSort
Source
https://www.geeksforgeeks.org/java-program-for-quicksort/
Java
1068
Chapter 150. Java Program for QuickSort
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = arr.length;
QuickSort ob = new QuickSort();
ob.sort(arr, 0, n-1);
System.out.println("sorted array");
printArray(arr);
}
}
/*This code is contributed by Rajat Mishra */
1069
Chapter 151
Recursion Idea.
Source
https://www.geeksforgeeks.org/java-program-for-recursive-bubble-sort/
1070
Chapter 151. Java Program for Recursive Bubble Sort
Java
Please refer complete article on Recursive Bubble Sort for more details!
1071
Chapter 152
Source
https://www.geeksforgeeks.org/java-program-for-recursive-insertion-sort/
Java
1072
Chapter 152. Java Program for Recursive Insertion Sort
{
// Base case
if (n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive( arr, n-1 );
// Insert last element at its correct position
// in sorted array.
int last = arr[n-1];
int j = n-2;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > last)
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = last;
}
// Driver Method
public static void main(String[] args)
{
int arr[] = {12, 11, 13, 5, 6};
insertionSortRecursive(arr, arr.length);
System.out.println(Arrays.toString(arr));
}
}
Please refer complete article on Recursive Insertion Sort for more details!
1073
Chapter 153
1074
Chapter 153. Java Program for Stooge Sort
// If there are more than 2 elements in
// the array
if (h-l+1 > 2)
{
int t = (h-l+1) / 3;
// Recursively sort first 2/3 elements
stoogesort(arr, l, h-t);
// Recursively sort last 2/3 elements
stoogesort(arr, l+t, h);
// Recursively sort first 2/3 elements
// again to confirm
stoogesort(arr, l, h-t);
}
}
// Driver Code
public static void main(String args[])
{
int arr[] = {2, 4, 5, 3, 1};
int n = arr.length;
stoogesort(arr, 0, n-1);
for (int i=0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
// Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:
1 2 3 4 5
Source
https://www.geeksforgeeks.org/java-program-for-stooge-sort/
1075
Chapter 154
Solution: In the optimum sequence of jobs, the total volume of goods left at the end of all
jobs is 222.503
Example-2:
Solution: In the optimum sequence of jobs the total volume of goods left at the end of all
jobs is 145.72
1076
Chapter 154. Job Selection Problem – Loss Minimization Strategy Set 2
Explanation –
Since this is an optimization problem, we can try to solve this problem by using a greedy
algorithm. On each day we make a selection from among the goods that are yet to be
produced. Thus all we need is a local selection criteria or heuristic, which when applied to
select the jobs will give us the optimum result.
Instead of trying to maximize the volume, we can also try to minimize the losses. Since the
total volume that can be obtained from all goods is also constant, if we minimize the losses
we are guaranteed to get the optimum answer.
Now consider any good having volume V
Loss after Day 1: PV
Loss after Day 2: PV + P(1-P)V or V(2P-P^2)
Loss after Day 3: V(2P-P^2) + P(1 – 2P + P^2)V or V(3P – 3P^2 + P^3)
As the day increases the losses too increase. So the trick would be to ensure that the goods
are not kept idle after production. Further, since we are required to produce at least one
job per day, we should perform low volume jobs, and then perform the high volume jobs.
This strategy works due to two factors.
So in order to obtain the optimum solution we produce the larger volume goods later on.
For the first day select the good with least volume and produce it. Remove the produced
good from the list of goods. For the next day repeat the same. Keep repeating while there
are goods left to be produced.
When calculating the total volume at the end of production, keep in mind the the
good produced on day i, will have times its volume left. Ev-
idently, the good produced on day N (last day) will have its volume intact since
.
Algorithm –
Complexity –
We perform exactly N push() and pop() operations each of which takes log (N) time. Hence
time complexity is O( N * log(N) ).
1077
Chapter 154. Job Selection Problem – Loss Minimization Strategy Set 2
#include <bits/stdc++.h>
using namespace std;
void optimum_sequence_jobs(vector<int>& V, double P)
{
int j = 1, N = V.size() - 1;
double result = 0;
// Create a min-heap (priority queue)
priority_queue<int, vector<int>, greater<int> > Queue;
// Add all goods to the the Queue
for (int i = 1; i <= N; i++)
Queue.push(V[i]);
// Pop Goods from Queue as long as it is not empty
while (!Queue.empty()) {
// Print the good
cout << Queue.top() << " ";
// Add the Queue to the vector
// so that total voulme can be calculated
V[j++] = Queue.top();
Queue.pop();
}
// Calclulating volume of goods left when all
// are produced. Move from right to left of
// sequence multiplying each volume by
// increasing powers of 1 - P starting from 0
for (int i = N; i >= 1; i--)
result += pow((1 - P), N - i) * V[i];
// Print result
cout << endl << result << endl;
}
// Driver code
int main()
{
// For implementation simplicity days are numbered
// from 1 to N. Hence 1 based indexing is used
vector<int> V{ -1, 3, 5, 4, 1, 2, 7, 6, 8, 9, 10 };
// 10% loss per day
1078
Chapter 154. Job Selection Problem – Loss Minimization Strategy Set 2
double P = 0.10;
optimum_sequence_jobs(V, P);
return 0;
}
Output –
1 2 3 4 5 6 7 8 9 10
41.3811
Source
https://www.geeksforgeeks.org/job-selection-problem-loss-minimization-strategy-set-2/
1079
Chapter 155
Input : L = {1, 2, 3, 5, 6}
T = {2, 4, 1, 3, 2}
Output : 3, 5, 4, 1, 2
Explanation: We should complete jobs
3, 5, 4, 1 and then 2 in this order.
Let us consider two extreme cases and we shall deduce the general case solution from them.
All jobs take same time to finish, i.e Ti = k for all i. Since all jobs take same time to finish
we should first select jobs which have large Loss (Li). We should select jobs which have the
1080
Chapter 155. Job Sequencing Problem – Loss Minimization
Source
https://www.geeksforgeeks.org/job-sequencing-problem-loss-minimization/
1081
Chapter 156
K-th smallest element after removing some integers from natural numbers - GeeksforGeeks
Given an array arr[] of size ‘n’ and a positive integer k. Consider series of natural numbers
and remove arr[0], arr[1], arr[2], …, arr[p] from it. Now the task is to find k-th smallest
number in the remaining set of natural numbers. If no such number exists print “-1”.
Examples :
Method 1 (Simple):
Make an auxiliary array b[] for presence/absence of natural numbers and initialize all with
0. Make all the integer equal to 1 which are present in array arr[] i.e b[arr[i]] = 1. Now, run
a loop and decrement k whenever unmarked cell is encountered. When the value of k is 0,
we get the answer.
Below is C++ implementation of this approach:
C++
1082
Chapter 156. K-th smallest element after removing some integers from natural numbers
Output :
1083
Chapter 156. K-th smallest element after removing some integers from natural numbers
Method 2 (Efficient):
First, sort the array arr[]. Observe, there will be arr[0] – 1 numbers between 0 and arr[0],
similarly, arr[1] – arr[0] – 1 numbers between arr[0] and arr[1] and so on. So, if k lies between
arr[i] – arr[i+1] – 1, then return K-th smallest element in the range. Else reduce k by arr[i]
– arr[i+1] – 1 i.e., k = k – (arr[i] – arr[i+1] – 1).
Algorithm to solve the problem:
// C++ program to find the Kth smallest element // after removing some integer from first n // n
Java
// Java program to find the // Kth smallest element after // removing some integer from // fi
C#
// C# program to find the // Kth smallest element after // removing some integer from // firs
PHP
<?php // PHP program to find the Kth // smallest element after // removing some integer from
Output :
More efficient method : K-th smallest element after removing given integers from natural
numbers Set 2
Improved By : jit_t
Source
https://www.geeksforgeeks.org/k-th-smallest-element-removing-integers-natural-numbers/
1084
Chapter 157
Know Your Sorting Algorithm Set 1 (Sorting Weapons used by Programming Languages) -
GeeksforGeeks
Ever wondered how sort() function we use in C++/Java or sorted() in Python work inter-
nally?
Here is a list of all the inbuilt sorting algorithms of different programming languages and
the algorithm they use internally.
1085
Chapter 157. Know Your Sorting Algorithm Set 1 (Sorting Weapons used by Programming
Languages)
• Stable- No
• Adaptive- No
1086
Chapter 157. Know Your Sorting Algorithm Set 1 (Sorting Weapons used by Programming
Languages)
In the next sets we will implement Introsort ( C++’s sorting weapon ) and Sleep sort,
Gnome Sort and other unconventional sorting algorithms.
Source
https://www.geeksforgeeks.org/know-sorting-algorithm-set-1-sorting-weapons-used-programming-languages/
1087
Chapter 158
Know Your Sorting Algorithm Set 2 (Introsort- C++’s Sorting Weapon) - GeeksforGeeks
We have discussed sorting weapons used by different languages in previous article. In this
article, C++’s Sorting Weapon, Introsort is discussed.
What is Introsort?
Simply putting, it is the best sorting algorithm around. It is a hybrid sorting algorithm,
which means that it uses more than one sorting algorithms as a routine.
Which standard sorting algorithms are used in Introsort
Introsort being a hybrid sorting algorithm uses three sorting algorithm to minimise the
running time, Quicksort, Heapsort and Insertion Sort
How does it work?
Introsort begins with quicksort and if the recursion depth goes more than a particular limit
it switches to Heapsort to avoid Quicksort’s worse case O(N2 ) time complexity. It also uses
insertion sort when the number of elements to sort is quite less.
So first it creates a partition. Three cases arises from here.
1. If the partition size is such that there is a possibility to exceed the maximum depth
limit then the Introsort switches to Heapsort. We define the maximum depth limit as
2*log(N)
2. If the partition size is too small then Quicksort decays to Insertion Sort. We define
this cutoff as 16 (due to research). So if the partition size is less than 16 then we will
do insertion sort.
3. If the partition size is under the limit and not too small (i.e- between 16 and 2*log(N)),
then it performs a simple quicksort.
1088
Chapter 158. Know Your Sorting Algorithm Set 2 (Introsort- C++’s Sorting Weapon)
1. It is a known and established fact that insertion sort is the most optimal comparison-
based sorting algorithm for small arrays.
2. It has a good locality of reference
3. It is an adaptive sorting algorithm, i.e- it outperforms all the other algorithms if the
array elements are partially sorted.
Why is cut-off 16 for switching from quick sort to insertion sort, and 2*logN for
switching from quick sort to heap sort ?
These values are chosen empirically as an approximate because of various tests and researches
conducted.
1089
Chapter 158. Know Your Sorting Algorithm Set 2 (Introsort- C++’s Sorting Weapon)
{
int *temp = a;
a = b;
b = temp;
return;
}
/* Function to sort an array using insertion sort*/
void InsertionSort(int arr[], int *begin, int *end)
{
// Get the left and the right index of the subarray
// to be sorted
int left = begin - arr;
int right = end - arr;
for (int i = left+1; i <= right; i++)
{
int key = arr[i];
int j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= left && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
return;
}
// A function to parition the array and return
// the partition point
int* Partition(int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
// increment index of smaller element
1090
Chapter 158. Know Your Sorting Algorithm Set 2 (Introsort- C++’s Sorting Weapon)
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return (arr + i + 1);
}
// A function that find the middle of the
// values pointed by the pointers a, b, c
// and return that pointer
int *MedianOfThree(int * a, int * b, int * c)
{
if (*a < *b && *b < *c)
return (b);
if (*a < *c && *c <= *b)
return (c);
if (*b <= *a && *a < *c)
return (a);
if (*b < *c && *c <= *a)
return (c);
if (*c <= *a && *a < *b)
return (a);
if (*c <= *b && *b <= *c)
return (b);
}
// A Utility function to perform intro sort
void IntrosortUtil(int arr[], int * begin,
int * end, int depthLimit)
{
// Count the number of elements
int size = end - begin;
// If partition size is low then do insertion sort
if (size < 16)
{
InsertionSort(arr, begin, end);
return;
}
1091
Chapter 158. Know Your Sorting Algorithm Set 2 (Introsort- C++’s Sorting Weapon)
1092
Chapter 158. Know Your Sorting Algorithm Set 2 (Introsort- C++’s Sorting Weapon)
// Pass the array, the pointer to the first element and
// the pointer to the last element
Introsort(arr, arr, arr+n-1);
printArray(arr, n);
return(0);
}
Output:
5 6 11 12 13
Is Introsort stable ?-
Since Quicksort is also not stable so Introsort is also not stable.
Time Complexity
Best Case – O(N log N)
Average Case- O(N log N)
Worse Case- O(N log N)
where, N = number of elements to be sorted.
Auxiliary Space
Just like quicksort, it may use O(log N) auxiliary recursion stack space.
Know Your Sorting Algorithm Set 2 (Introsort- C++’s Sorting Weapon)
References
https://en.wikipedia.org/wiki/Introsort
Improved By : callmeHK
Source
https://www.geeksforgeeks.org/know-your-sorting-algorithm-set-2-introsort-cs-sorting-weapon/
1093
Chapter 159
A simple solution is to run two loops. The outer loop picks all elements one by one. The
inner loop finds frequency of the picked element and compares with the minimum so far.
Time complexity of this solution is O(n2 )
A better solution is to do sorting. We first sort the array, then linearly traverse the array.
C++
1094
Chapter 159. Least frequent element in an array
Java
1095
Chapter 159. Least frequent element in an array
Python3
1096
Chapter 159. Least frequent element in an array
def leastFrequent(arr, n) :
# Sort the array
arr.sort()
# find the min frequency using
# linear traversal
min_count = n + 1
res = -1
curr_count = 1
for i in range(1, n) :
if (arr[i] == arr[i - 1]) :
curr_count = curr_count + 1
else :
if (curr_count < min_count) :
min_count = curr_count
res = arr[i - 1]
curr_count = 1
# If last element is least frequent
if (curr_count < min_count) :
min_count = curr_count
res = arr[n - 1]
return res
# Driver program
arr = [1, 3, 2, 1, 2, 2, 3, 1]
n = len(arr)
print(leastFrequent(arr, n))
# This code is contributed
# by Nikita Tiwari.
C#
1097
Chapter 159. Least frequent element in an array
{
// Sort the array
Array.Sort(arr);
// find the min frequency
// using linear traversal
int min_count = n + 1, res = -1;
int curr_count = 1;
for (int i = 1; i < n; i++)
{
if (arr[i] == arr[i - 1])
curr_count++;
else
{
if (curr_count < min_count)
{
min_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is least frequent
if (curr_count < min_count)
{
min_count = curr_count;
res = arr[n - 1];
}
return res;
}
// Driver code
static public void Main ()
{
int[] arr = {1, 3, 2, 1, 2, 2, 3, 1};
int n = arr.Length;
// Function calling
Console.Write(leastFrequent(arr, n));
}
}
// This code is contributed by Shrikant13
1098
Chapter 159. Least frequent element in an array
PHP
<?php
// PHP program to find the
// least frequent element
// in an array.
function leastFrequent($arr, $n)
{
// Sort the array
sort($arr);
sort($arr , $n);
// find the min frequency
// using linear traversal
$min_count = $n + 1;
$res = -1;
$curr_count = 1;
for($i = 1; $i < $n; $i++)
{
if ($arr[$i] == $arr[$i - 1])
$curr_count++;
else
{
if ($curr_count < $min_count)
{
$min_count = $curr_count;
$res = $arr[$i - 1];
}
$curr_count = 1;
}
}
// If last element is
// least frequent
if ($curr_count < $min_count)
{
$min_count = $curr_count;
$res = $arr[$n - 1];
}
return $res;
}
// Driver Code
{
$arr = array(1, 3, 2, 1, 2, 2, 3, 1);
1099
Chapter 159. Least frequent element in an array
Output:
1100
Chapter 159. Least frequent element in an array
{
int arr[] = {1, 3, 2, 1, 2, 2, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
cout << leastFrequent(arr, n);
return 0;
}
Java
1101
Chapter 159. Least frequent element in an array
return res;
}
// driver program
public static void main (String[] args) {
int arr[] = {1, 3, 2, 1, 2, 2, 3, 1};
int n = arr.length;
System.out.println(leastFrequent(arr,n));
}
}
// This code is contributed by Akash Singh.
C#
1102
Chapter 159. Least frequent element in an array
Output:
Source
https://www.geeksforgeeks.org/least-frequent-element-array/
1103
Chapter 160
Lexicographical concatenation
of all substrings of a string
Input : s = “abc”
Output : aababcbbcc
The substrings of s in lexicographic order are “a”, “b”, “c”, “ab”, “abc”, “bc”.
Concatenation of substrings is “a”+”ab”+”abc”+”b”+”bc”+”c” = “aababcb-
bcc”.
Input : s = “cba”
Output : abbaccbcba
1. Find all the substrings of string and store it in a string array. The size of array would be
n*(n+1)/2 where n is length of input string.
2. Sort the string array to make them all in lexicographical order.
3. Concatenate the strings of string array in another empty string.
1104
Chapter 160. Lexicographical concatenation of all substrings of a string
Output:
aababcbbcc
Source
https://www.geeksforgeeks.org/lexicographical-concatenation-substrings-string/
1105
Chapter 161
Lexicographically smallest
string obtained after
concatenating array
One might think that sorting the given strings in the lexicographical order and then concate-
nating them produces the correct output. This approach produces the correct output for
inputs like [“a”, “ab”, “abc”]. However, applying this method on [“c”, “cb”, “cba”] produces
the wrong input and hence this approach is incorrect.
The correct approach is to use a regular sorting algorithm. When two strings a and b are
compared to decide if they have to be swapped or not, do not check if a is lexicographically
smaller than b or not. Instead check if appending b at the end of a produces a lexicograph-
ically smaller string or appending a at the end of b does. This approach works because we
want the concatenated string to be lexicographically small, not the individual strings to be
1106
Chapter 161. Lexicographically smallest string obtained after concatenating array
Java
1107
Chapter 161. Lexicographically smallest string obtained after concatenating array
1108
Chapter 161. Lexicographically smallest string obtained after concatenating array
C#
// C# code to find
// the lexicographically
// smallest string
using System;
class GFG {
// function to sort the
// array of string
static void sort(String []a, int n)
{
//sort the array
for(int i = 0;i < n;i++)
{
for(int j = i + 1;j < n;j++)
{
// comparing which of the
// two concatenation causes
// lexiographically smaller
// string
if((a[i] + a[j]).CompareTo(a[j] +
a[i]) > 0)
{
String s = a[i];
a[i] = a[j];
a[j] = s;
}
}
}
}
static String lexsmallest(String []a, int n)
{
// Sort strings
sort(a,n);
// Concatenating sorted
// strings
String answer = "";
for (int i = 0; i < n; i++)
answer += a[i];
1109
Chapter 161. Lexicographically smallest string obtained after concatenating array
return answer;
}
// Driver code
public static void Main()
{
String []a = {"c", "cb", "cba"};
int n = 3;
Console.Write("lexiographically smallest string = "
+ lexsmallest(a, n));
}
}
// This code is contributed by nitin mittal
Output:
cbacbc
Time complexity : The above code runs inO(M * N * logN) where N is number of strings
and M is maximum length of a string.
Improved By : andrew1234, nitin mittal
Source
https://www.geeksforgeeks.org/lexicographically-smallest-string-obtained-concatenating-array/
1110
Chapter 162
The longest common prefix for an array of strings is the common prefix between 2 most
dissimilar strings. For example, in the given array {“apple”, “ape”, “zebra”}, there is no
common prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not
share any starting characters.
We have discussed five different approaches in below posts.
In this post a new method based on sorting is discussed. The idea is to sort the array of
strings and find the common prefix of the first and last string of the sorted array.
Java
1111
Chapter 162. Longest Common Prefix using Sorting
C#
1112
Chapter 162. Longest Common Prefix using Sorting
public class GFG {
static string longestCommonPrefix(String[] a)
{
int size = a.Length;
/* if size is 0, return empty string */
if (size == 0)
return "";
if (size == 1)
return a[0];
/* sort the array of strings */
Array.Sort(a);
/* find the minimum length from first
and last string */
int end = Math.Min(a[0].Length,
a[size-1].Length);
/* find the common prefix between the
first and last string */
int i = 0;
while (i < end && a[0][i] == a[size-1][i] )
i++;
string pre = a[0].Substring(0, i);
return pre;
}
/* Driver Function to test other function */
public static void Main()
{
string[] input = {"geeksforgeeks", "geeks",
"geek", "geezer"};
Console.WriteLine( "The longest Common"
+ " Prefix is : "
+ longestCommonPrefix(input));
}
}
// This code is contributed by Sam007.
Output:
1113
Chapter 162. Longest Common Prefix using Sorting
Time Complexity: O(MAX * n * log n ) where n is the number of strings in the array
and MAX is maximum number of characters in any string.
Improved By : Sam007
Source
https://www.geeksforgeeks.org/longest-common-prefix-using-sorting/
1114
Chapter 163
Longest Consecutive
Subsequence
Input: arr[] = {36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42}
Output: 5
The subsequence 36, 35, 33, 34, 32 is the longest subsequence
of consecutive elements.
One Solution is to first sort the array and find the longest subarray with consecutive
elements. Time complexity of this solution is O(nLogn). Thanks to Hao.W for suggesting
this solution.
We can solve this problem in O(n) time using an Efficient Solution. The idea is to use
Hashing. We first insert all elements in a Hash. Then check all the possible starts of
consecutive subsequences. Below is complete algorithm.
1115
Chapter 163. Longest Consecutive Subsequence
1116
Chapter 163. Longest Consecutive Subsequence
}
return ans;
}
// Driver program
int main()
{
int arr[] = {1, 9, 3, 10, 4, 20, 2};
int n = sizeof arr/ sizeof arr[0];
cout << "Length of the Longest contiguous subsequence is "
<< findLongestConseqSubseq(arr, n);
return 0;
}
Java
1117
Chapter 163. Longest Consecutive Subsequence
if (ans<j-arr[i])
ans = j-arr[i];
}
}
return ans;
}
// Testing program
public static void main(String args[])
{
int arr[] = {1, 9, 3, 10, 4, 20, 2};
int n = arr.length;
System.out.println("Length of the Longest consecutive subsequence is " +
findLongestConseqSubseq(arr,n));
}
}
// This code is contributed by Aakash Hasija
Python
1118
Chapter 163. Longest Consecutive Subsequence
ans=max(ans, j-arr[i])
return ans
# Driver function
if __name__=='__main__':
n = 7
arr = [1, 9, 3, 10, 4, 20, 2]
print "Length of the Longest contiguous subsequence is ",
print findLongestConseqSubseq(arr, n)
# Contributed by: Harshit Sidhwa
Output:
Time Complexity: At first look, time complexity looks more than O(n). If we take a
closer look, we can notice that it is O(n) under the assumption that hash insert and search
take O(1) time. The function S.find() inside the while loop is called at most twice for every
element. For example, consider the case when all array elements are consecutive. In this
case, the outer find is called for every element, but we go inside the if condition only for the
smallest element. Once we are inside the if condition, we call find() one more time for every
other element.
Thanks to Gaurav Ahirwar for above solution.
Source
https://www.geeksforgeeks.org/longest-consecutive-subsequence/
1119
Chapter 164
In the above example after 3rd iteration of the loop max value is 7, which holds true for first
3 elements of array A. Here, the loop invariant condition is that max is always maximum
among the first i elements of array A.
Loop Invariant condition of various algorithms:
Prerequisite: insertion sort, selection sort, quick sort, bubblesort,
Selection Sort:
In selection sort algorithm we find the minimum element from the unsorted part and put it
at the beginning.
min_idx = 0
1120
Chapter 164. Loop Invariant Condition with Examples of Sorting Algorithms
{
min_idx = i;
for (j = i+1 to n-1)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
In the above pseudo code there are two loop invariant condition:
1. In the outer loop, array is sorted for first i elements.
2. In the inner loop, min is always the minimum value in A[i to j].
Insertion Sort:
In insertion sort, loop invariant condition is that the subarray A[0 to i-1] is always sorted.
for (i = 1 to n-1)
{
key = arr[i];
j = i-1;
while (j >= 0 and arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
Quicksort:
In quicksort algorithm, after every partition call array is divided into 3 regions:
1. Pivot element is placed at its correct position.
2. Elements less than pivot element lie on the left side of pivot element.
3. Elements greater than pivot element lie on the right side of pivot element.
1121
Chapter 164. Loop Invariant Condition with Examples of Sorting Algorithms
pivot = arr[high];
i = (low - 1)
for (j = low; j <= high- 1; j++)
if (arr[j] <= pivot)
i++;
swap arr[i] and arr[j]
swap arr[i + 1] and arr[high])
return (i + 1)
}
Bubble Sort:
In bubble sort algorithm, after each iteration of the loop largest element of the array is
always placed at right most position. Therefore, the loop invariant condition is that at the
end of i iteration right most i elements are sorted and in place.
for (i = 0 to n-1)
for (j = 0 to j arr[j+1])
swap(&arr[j], &arr[j+1]);
Source
https://www.geeksforgeeks.org/loop-invariant-condition-examples-sorting-algorithms/
1122
Chapter 165
1) Each of the n! permutations on n elements must appear as one of the leaves of the
decision tree for the sorting algorithm to sort properly.
1123
Chapter 165. Lower bound for comparison based sorting algorithms
Therefore, any comparison based sorting algorithm must make at least nLog2 n comparisons
to sort the input array, and Heapsort and merge sort are asymptotically optimal comparison
sorts.
References:
Introduction to Algorithms, by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest
and Clifford Stein
Source
https://www.geeksforgeeks.org/lower-bound-on-comparison-based-sorting-algorithms/
1124
Chapter 166
Input : a = { 3, 1, 1 }, b = { 1, 2, 2 }
Output : 2
Explanation : Here we can increase any 1 into 2 by 1 operation and 3 to 2 in
one decrement operation. So a[] becomes {2, 2, 1} which is a permutation of b[].
Input : a = { 3, 1, 1 }, b = { 1, 1, 2 }
Output : 1
Algorithm :
1. First sort both the arrays.
2. After sorting we will run a loop in which we compare the first and second array elements
and calculate the required operation needed to make first array equal to second.
Below is implementation of the above approach
C++
1125
Chapter 166. Making elements of two arrays same with minimum increment/decrement
#include <bits/stdc++.h>
using namespace std;
int MinOperation(int a[], int b[], int n)
{
// sorting both arrays in
// ascending order
sort(a, a + n);
sort(b, b + n);
// variable to store the
// final result
int result = 0;
// After sorting both arrays
// Now each array is in non-
// decreasing order. Thus,
// we will now compare each
// element of the array and
// do the increment or decrement
// operation depending upon the
// value of array b[].
for (int i = 0; i < n; ++i) {
if (a[i] > b[i])
result = result + abs(a[i] - b[i]);
else if (a[i] < b[i])
result = result + abs(a[i] - b[i]);
}
return result;
}
// Driver code
int main()
{
int a[] = { 3, 1, 1 };
int b[] = { 1, 2, 2 };
int n = sizeof(a) / sizeof(a[0]);
cout << MinOperation(a, b, n);
return 0;
}
Java
1126
Chapter 166. Making elements of two arrays same with minimum increment/decrement
import java.util.Arrays;
import java.io.*;
class GFG
{
static int MinOperation(int a[],
int b[],
int n)
{
// sorting both arrays
// in ascending order
Arrays.sort(a);
Arrays.sort(b);
// variable to store
// the final result
int result = 0;
// After sorting both arrays
// Now each array is in non-
// decreasing order. Thus,
// we will now compare each
// element of the array and
// do the increment or decrement
// operation depending upon the
// value of array b[].
for (int i = 0; i < n; ++i)
{
if (a[i] > b[i])
result = result +
Math.abs(a[i] - b[i]);
else if (a[i] < b[i])
result = result +
Math.abs(a[i] - b[i]);
}
return result;
}
// Driver code
public static void main (String[] args)
{
int a[] = {3, 1, 1};
int b[] = {1, 2, 2};
int n = a.length;
System.out.println(MinOperation(a, b, n));
1127
Chapter 166. Making elements of two arrays same with minimum increment/decrement
}
}
// This code is contributed
// by akt_mit
PHP
<?php
// PHP program to find minimum
// increment/decrement operations
// to make array elements same.
function MinOperation($a, $b, $n)
{
// sorting both arrays in
// ascending order
sort($a);
sort($b);
// variable to store
// the final result
$result = 0;
// After sorting both arrays
// Now each array is in non-
// decreasing order. Thus,
// we will now compare each
// element of the array and
// do the increment or decrement
// operation depending upon the
// value of array b[].
for ($i = 0; $i < $n; ++$i)
{
if ($a[$i] > $b[$i])
$result = $result + abs($a[$i] -
$b[$i]);
else if ($a[$i] < $b[$i])
$result = $result + abs($a[$i] -
$b[$i]);
}
return $result;
}
// Driver code
$a = array ( 3, 1, 1 );
1128
Chapter 166. Making elements of two arrays same with minimum increment/decrement
$b = array ( 1, 2, 2 );
$n = sizeof($a);
echo MinOperation($a, $b, $n);
// This code is contributed by ajit
?>
Output :
Source
https://www.geeksforgeeks.org/making-elements-of-two-arrays-same-with-minimum-incrementdecrement/
1129
Chapter 167
Maximise the number of toys that can be purchased with amount K - GeeksforGeeks
Given an array consisting of cost of toys. Given an integer K depicting the amount of money
available to purchase toys. Write a program to find the maximum number of toys one can
buy with the amount K.
Note: One can buy only 1 quantity of a particular toy.
Examples :
Input: N = 10, K = 50
cost = { 1, 12, 5, 111, 200, 1000, 10, 9, 12, 15 }
Output: 6
Explanation: Toys with amount 1, 5, 9, 10, 12, and 12
can be purchased resulting in a total amount of 49. Hence,
maximum number of toys is 6.
Input: N = 7, K = 50
cost = { 1, 12, 5, 111, 200, 1000, 10 }
Output: 4
The idea to solve this problem is to first sort the cost array in ascending order. This will
arrange the toys in increasing order of the cost. Now iterate over the cost array and keep
calculating the sum of costs until the sum is less than or equal to K. Finally return the
number of toys used to calculate the sum which is just less than or equals to K.
Below is the implementation of above approach:
C++
1130
Chapter 167. Maximise the number of toys that can be purchased with amount K
Java
1131
Chapter 167. Maximise the number of toys that can be purchased with amount K
{
// This functions returns
// the required number of toys
static int maximum_toys(int cost[],
int N, int K)
{
int count = 0, sum = 0;
// sort the cost array
Arrays.sort(cost);
for (int i = 0; i < N; i++)
{
// If the array element is less
// then K add it to prefix sum
// and check this prefix sum is
// less then given K
if (cost[i] < K && sum <= K)
{
sum = sum + cost[i];
// Increment the
// count variable
if (sum <= K)
count++;
}
}
return count;
}
// Driver Code
public static void main (String[] args)
{
int K = 50;
int cost[] = {1, 12, 5, 111, 200,
1000, 10, 9, 12, 15};
int N = cost.length;
System.out.print( maximum_toys(cost, N, K));
}
}
// This code is contributed by anuj_67.
C#
1132
Chapter 167. Maximise the number of toys that can be purchased with amount K
using System;
class GFG
{
// This functions returns
// the required number of toys
static int maximum_toys(int []cost,
int N, int K)
{
int count = 0, sum = 0;
// sort the cost array
Array.Sort(cost);
for (int i = 0; i < N; i++)
{
// If the array element is less
// then K add it to prefix sum
// and check this prefix sum is
// less then given K
if (cost[i] < K && sum <= K)
{
sum = sum + cost[i];
// Increment the
// count variable
if (sum <= K)
count++;
}
}
return count;
}
// Driver Code
public static void Main ()
{
int K = 50;
int []cost = {1, 12, 5, 111, 200,
1000, 10, 9, 12, 15};
int N = cost.Length;
Console.Write( maximum_toys(cost, N, K));
}
}
// This code is contributed by anuj_67.
PHP
1133
Chapter 167. Maximise the number of toys that can be purchased with amount K
<?php
// PHP Program to maximize the
// number of toys with K amount
// This functions returns
// the required number of toys
function maximum_toys($cost, $N, $K)
{
$count = 0; $sum = 0;
// sort the cost array
sort($cost);
for ($i = 0; $i < $N; $i++)
{
// If the array element is less
// then K add it to prefix sum
// and check this prefix sum is
// less then given K
if ($cost[$i] < $K and $sum <= $K)
{
$sum = $sum + $cost[$i];
// Increment the
// count variable
if ($sum <= $K)
$count++;
}
}
return $count;
}
// Driver Code
$K = 50;
$cost = array(1, 12, 5, 111, 200,
1000, 10, 9, 12, 15 );
$N = count($cost);
echo maximum_toys($cost, $N, $K),"\n";
// This code is contributed by anuj_67
?>
Output :
1134
Chapter 167. Maximise the number of toys that can be purchased with amount K
Source
https://www.geeksforgeeks.org/maximise-the-number-of-toys-that-can-be-purchased-with-amount-k/
1135
Chapter 168
Approach : We create an auxiliary array of size 2*n and store the elements of 2nd array
in auxiliary array, and then we will store elements of 1st array in it. After that we will
sort auxiliary array in decreasing order. To keep the order of elements according to input
arrays we will use hash table. We will store 1st n largest unique elements of auxiliary array
in hash table. Now we traverse the second array and store that elements of second array
in auxiliary array that are present in hash table. Similarly we will traverse first array and
store the elements that are present in hash table. In this way we get n unique and largest
elements from both the arrays in auxiliary array while keeping the order of appearance of
elements same.
Below is the implementation of above approach :
1136
Chapter 168. Maximize elements using another array
1137
Chapter 168. Maximize elements using another array
// if arr2 element is present in hash,
// store it in arr3
if (hash.find(arr2[i]) != hash.end()) {
arr3[k++] = arr2[i];
hash.erase(arr2[i]);
}
}
// store that elements of arr1 in arr3
// that are present in hash
for (int i = 0; i < n; i++) {
// if arr1 element is present in hash,
// store it in arr3
if (hash.find(arr1[i]) != hash.end()) {
arr3[k++] = arr1[i];
hash.erase(arr1[i]);
}
}
// copying 1st n elements of arr3 to arr1
for (int i = 0; i < n; i++)
arr1[i] = arr3[i];
}
// Function to print array elements
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver Code
int main()
{
int array1[] = { 7, 4, 8, 0, 1 };
int array2[] = { 9, 7, 2, 3, 6 };
int size = sizeof(array1) / sizeof(array1[0]);
maximizeArray(array1, array2, size);
printArray(array1, size);
}
Output:
9 7 6 4 8
1138
Chapter 168. Maximize elements using another array
Source
https://www.geeksforgeeks.org/maximize-elements-using-another-array/
1139
Chapter 169
Input : arr[] = { 4, 2, 1, 8 }
Output : 18
Rearrange given array as : { 1, 8, 2, 4 }
Sum of difference between consecutive element
= |1 - 8| + |8 - 2| + |2 - 4| + |4 - 1|
= 7 + 6 + 2 + 3
= 18.
The idea is to use Greedy Approach and try to bring elements having greater difference
closer.
Consider the sorted permutation of the given array a1 , a1 , a2 ,…., an – 1 , an such that a1 <
a2 < a3 …. < an – 1 < an .
Now, to obtain the answer having maximum sum of difference between consecutive element,
arrange element in following manner:
a1 , an , a2 , an-1 ,…., an/2 , a(n/2) + 1
We can observe that the arrangement produces the optimal answer, as all a1 , a2 , a3 ,…..,
a(n/2)-1 , an/2 are subtracted twice while a(n/2)+1 , a(n/2)+2 , a(n/2)+3 ,….., an – 1 , an are added
1140
Chapter 169. Maximize sum of consecutive differences in a circular array
twice.
C++
Java
1141
Chapter 169. Maximize sum of consecutive differences in a circular array
Python3
1142
Chapter 169. Maximize sum of consecutive differences in a circular array
sum -= (2 * arr[i])
sum += (2 * arr[n - i - 1])
return sum
# Driver Program
arr = [4, 2, 1, 8]
n = len(arr)
print (maxSum(arr, n))
# This code is contributed by Shreyanshi Arun.
C#
1143
Chapter 169. Maximize sum of consecutive differences in a circular array
}
//This Code is contributed by vt_m.
Output :
18
Source
https://www.geeksforgeeks.org/maximize-sum-consecutive-differences-circular-array/
1144
Chapter 170
Input: N = 5, M = 3
CP[]= {5, 10, 35, 7, 23}
SP[] = {11, 10, 0, 9, 19}
Output: 8
Profit on 0th product i.e. 11-5 = 6
Profit on 3rd product i.e. 9-7 = 2
Selling any other product will not give profit.
So, total profit = 6+2 = 8.
Input: N = 4, M = 2
CP[] = {17, 9, 8, 20}
SP[] = {10, 9, 8, 27}
Output: 7
Approach:
1. Store the profit/loss on buying and selling of each product i.e. SP[i]-CP[i] in an
array.
2. Sort that array in descending order.
3. Add the positive values up to M values as positive values denote profit.
4. Return Sum.
1145
Chapter 170. Maximize the profit by selling at-most M products
Java
1146
Chapter 170. Maximize the profit by selling at-most M products
1147
Chapter 170. Maximize the profit by selling at-most M products
Python3
# Python3 implementation
# of above approach
# Function to find profit
def solve(N, M, cp, sp) :
# take empty list
profit = []
# Calculating profit
# for each gadget
for i in range(N) :
profit.append(sp[i] - cp[i])
# sort the profit array
# in decending order
profit.sort(reverse = True)
sum = 0
# check for best M profits
for i in range(M) :
if profit[i] > 0 :
sum += profit[i]
else :
break
return sum
# Driver Code
if __name__ == "__main__" :
N, M = 5, 3
CP = [5, 10, 35, 7, 23]
SP = [11, 10, 0, 9, 19]
# function calling
print(solve(N, M, CP, SP))
# This code is contributed
# by ANKITRAI1
C#
1148
Chapter 170. Maximize the profit by selling at-most M products
1149
Chapter 170. Maximize the profit by selling at-most M products
Source
https://www.geeksforgeeks.org/maximize-the-profit-by-selling-at-most-m-products/
1150
Chapter 171
Input : N = 4, arr[] = { 3, 5, 6, 1 }
Output : 31
If we arrange arr[] as { 1, 3, 5, 6 }.
Sum of arr[i]*i is 1*0 + 3*1 + 5*2 + 6*3
= 31, which is maximum
A simple solution is to generate all permutations of given array. For every permutation,
compute the value of Σarr[i]*i and finally return the maximum value.
An efficient solution is based on the fact that the largest value should be scaled maximum
and smallest value should be scaled minimum. So we multiply minimum value of i with
minimum value of arr[i]. So, sort the given array in increasing order and compute the sum
of ari]*i, where i = 0 to n-1.
Below is the implementation of this approach:
C++
1151
Chapter 171. Maximize the sum of arr[i]*i
Java
1152
Chapter 171. Maximize the sum of arr[i]*i
int n = arr.length;
System.out.println(maxSum(arr, n));
}
}
// This code is contributed by Prerna Saini
Python3
C#
1153
Chapter 171. Maximize the sum of arr[i]*i
Array.Sort(arr);
// Finding the sum of arr[i]*i
int sum = 0;
for (int i = 0; i < n; i++)
sum += (arr[i] * i);
return sum;
}
// Driver code
static public void Main()
{
int[] arr = {3, 5, 6, 1};
int n = arr.Length;
Console.WriteLine(maxSum(arr, n));
}
}
// This code is contributed by Ajit.
PHP
<?php
// PHP program to find the
// maximum value of i*arr[i]
// function returns the
// maximum value of i*arr[i]
function maxSum($arr, $n)
{
// Sort the array
sort($arr);
// Finding the sum
// of arr[i]*i
$sum = 0;
for ($i = 0; $i < $n; $i++)
$sum += ($arr[$i] * $i);
return $sum;
}
// Driver Code
$arr = array( 3, 5, 6, 1 );
$n = count($arr);
1154
Chapter 171. Maximize the sum of arr[i]*i
echo maxSum($arr, $n);
// This code is contributed by anuj_67.
?>
Output:
31
Source
https://www.geeksforgeeks.org/maximize-sum-arrii/
1155
Chapter 172
Simple Approach: By taking few examples, we can observe that if we sort both array.
Then one by pick closest feasible element for every element, we get the optimal answer.
In this approach we first sort both the arrays and then compare each element of the first
array with each element of the second array for the possible pair, if it’s possible to form a
pair, we form the pair and move to check for the next possible pair for the next element of
the first array.
1156
Chapter 172. Maximizing Unique Pairs from two arrays
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
// Returns count of maximum pairs that caan
// be formed from a[] and b[] under given
// constraints.
ll findMaxPairs(ll a[], ll b[], ll n, ll k)
{
sort(a, a+n); // Sorting the first array.
sort(b, b+n); // Sorting the second array.
// To keep track of visited elements of b[]
bool flag[n];
memset(flag, false, sizeof(flag));
// For every element of a[], find a pair
// for it and break as soon as a pair is
// found.
int result = 0;
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (abs(a[i]-b[j])<=k && flag[j]==false)
{
// Increasing the count if a pair is formed.
result++;
/* Making the corresponding flag array
element as 1 indicating the element
in the second array element has
been used. */
flag[j] = true;
// We break the loop to make sure an
// element of a[] is used only once.
break;
}
}
}
return result;
}
// Driver code
int main()
{
ll a[] = {10, 15, 20}, b[] = {17, 12, 24};
1157
Chapter 172. Maximizing Unique Pairs from two arrays
int n = sizeof(a)/sizeof(a[0]);
int k = 3;
cout << findMaxPairs(a, b, n, k);
return 0;
}
Output:
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
// Returns count of maximum pairs that caan
// be formed from a[] and b[] under given
// constraints.
ll findMaxPairs(ll a[], ll b[], ll n, ll k)
{
sort(a, a+n); // Sorting the first array.
sort(b, b+n); // Sorting the second array.
int result = 0;
for (int i=0, j=0; i<n && j<n;)
{
if (abs(a[i] - b[j]) <= k)
{
result++;
// Increasing array pointer of
// both the first and the second array.
i++;
j++;
}
// Increasing array pointer of the second array.
else if(a[i] > b[j])
j++;
// Increasing array pointer of the first array.
1158
Chapter 172. Maximizing Unique Pairs from two arrays
else
i++;
}
return result;
}
// Driver code
int main()
{
ll a[] = {10, 15, 20};
ll b[] = {17, 12, 24};
int n = sizeof(a)/sizeof(a[0]);
int k = 3;
cout << findMaxPairs(a, b, n, k);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximizing-unique-pairs-two-arrays/
1159
Chapter 173
Method 1 (Sorting)
The task basically reduces to finding two pairs of equal values in array. If there are more
than two pairs, then pick the two pairs with maximum values. A simple solution is to do
following.
1) Sort the given array.
2) Traverse array from largest to smallest value and return two pairs with maximum values.
C++
1160
Chapter 173. Maximum area rectangle by picking four sides from array
// function for finding max area
int findArea(int arr[], int n)
{
// sort array in non-increasing order
sort(arr, arr + n, greater<int>());
// Initialize two sides of rectangle
int dimension[2] = { 0, 0 };
// traverse through array
for (int i = 0, j = 0; i < n - 1 && j < 2; i++)
// if any element occurs twice
// store that as dimension
if (arr[i] == arr[i + 1])
dimension[j++] = arr[i++];
// return the product of dimensions
return (dimension[0] * dimension[1]);
}
// driver function
int main()
{
int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findArea(arr, n);
return 0;
}
Java
1161
Chapter 173. Maximum area rectangle by picking four sides from array
// traverse through array
for (int i = 0, j = 0; i < n - 1 && j < 2;
i++)
// if any element occurs twice
// store that as dimension
if (arr[i] == arr[i + 1])
dimension[j++] = arr[i++];
// return the product of dimensions
return (dimension[0] * dimension[1]);
}
// driver function
public static void main(String args[])
{
Integer arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };
int n = arr.length;
System.out.println(findArea(arr, n));
}
}
// This code is contributed by Sumit Ghosh
Python3
1162
Chapter 173. Maximum area rectangle by picking four sides from array
PHP
<?php
// PHP program for finding maximum area possible
// of a rectangle
// function for finding max area
function findArea($arr, $n)
{
// sort array in non-
// increasing order
rsort($arr);
// Initialize two sides
// of rectangle
$dimension = array( 0, 0 );
// traverse through array
for( $i = 0, $j = 0; $i < $n - 1 &&
$j < 2; $i++)
// if any element occurs twice
// store that as dimension
if ($arr[$i] == $arr[$i + 1])
$dimension[$j++] = $arr[$i++];
// return the product
1163
Chapter 173. Maximum area rectangle by picking four sides from array
// of dimensions
return ($dimension[0] *
$dimension[1]);
}
// Driver Code
$arr = array(4, 2, 1, 4, 6, 6, 2, 5);
$n =count($arr);
echo findArea($arr, $n);
// This code is contributed by anuj_67.
?>
Output:
24
Method 2 (Hashing)
The idea is to insert all first occurrences of elements in a hash set. For second occurrences,
keep track of maximum two values.
C++
1164
Chapter 173. Maximum area rectangle by picking four sides from array
Java
1165
Chapter 173. Maximum area rectangle by picking four sides from array
// If this is second (or more)
// occurrence, update first and
// second maximum values.
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second)
second = arr[i];
}
// return the product of dimensions
return (first * second);
}
// driver function
public static void main(String args[])
{
int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };
int n = arr.length;
System.out.println(findArea(arr, n));
}
}
// This code is contributed by Sumit Ghosh
Output:
24
Source
https://www.geeksforgeeks.org/maximum-area-rectangle-picking-four-sides-array/
1166
Chapter 174
Maximum array from two given arrays keeping order same - GeeksforGeeks
Given two same sized arrays A[] and B[] (both arrays contain distinct elements individually
but may have some common elements), task is to form a third (or result) array of same size.
The result array should have maximum n elements from both array. It should have chosen
elements of A[] first, then chosen elements of B[] in same order as they appear in original
arrays. If there are common elements, then only one element should be present in res[] and
priority should be given to A[].
Examples:
Input : A[] = [ 9 7 2 3 6 ]
B[] = [ 7 4 8 0 1 ]
Output : res[] = [9 7 6 4 8]
res[] has maximum n elements of both A[]
and B[] such that elements of A[] appear
first (in same order), then elements of B[].
Also 7 is common and priority is given to
A's 7.
Input : A[] = [ 6 7 5 3 ]
B[] = [ 5 6 2 9 ]
Output : res[] = [ 6 7 5 9 ]
1) Create copies of both arrays and sort the copies in decreasing order.
2) Use a hash to pick unique n maximum elements of both arrays, giving priority to A[].
3) Initialize result array as empty.
4) Traverse through A[], copy those elements of A[] that are present in the hash. This is
done to keep order of elements same.
1167
Chapter 174. Maximum array from two given arrays keeping order same
5) Repeat step 4 for B[]. This time we only consider those elements that are not present in
A[] (Do not appear twice in hash).
Below c++ implementation of above idea.
1168
Chapter 174. Maximum array from two given arrays keeping order same
Output:
9 7 6 4 8
Source
https://www.geeksforgeeks.org/maximum-array-from-two-given-arrays-keeping-order-same/
1169
Chapter 175
Maximum difference between frequency of two elements such that element having greater
frequency is also greater - GeeksforGeeks
Given an array of n positive integers with many repeating elements. The task is to find
maximum difference between the frequency of any two different elements, such that the
element with greater frequency is also greater in value than the second integer.
Examples:
Input : arr[] = { 3, 1, 3, 2, 3, 2 }.
Output : 2
Frequency of 3 = 3.
Frequency of 2 = 2.
Frequency of 1 = 1.
Here difference of frequency of element 3 and 1 is = 3 - 1 = 2.
Also 3 > 1.
1170
Chapter 175. Maximum difference between frequency of two elements such that element
having greater frequency is also greater
1171
Chapter 175. Maximum difference between frequency of two elements such that element
having greater frequency is also greater
Output:
1172
Chapter 175. Maximum difference between frequency of two elements such that element
having greater frequency is also greater
int min_freq = n+1;
// Iterate through all sorted distinct elements.
// For each distinct element, maintaining the
// element with minimum frequency than that
// element and also finding the maximum
// frequency difference
int ans = 0;
for (int i=0; i<j; i++)
{
int cur_freq = freq[dist[i]];
ans = max(ans, cur_freq - min_freq);
min_freq = min(min_freq, cur_freq);
}
return ans;
}
// Driven Program
int main()
{
int arr[] = { 3, 1, 3, 2, 3, 2 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxdiff(arr, n) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximum-difference-between-frequency-of-two-elements-such-that-element-having-
1173
Chapter 176
Simple Approach: We can solve this problem by making all possible combinations and
checking each set of combination difference between the group with highest sum and with
the lowest sum. A total of n*(n-1)/2 such groups would be formed (nC2).
1174
Chapter 176. Maximum difference between groups of size two
Time Complexity: O(n^3), because it will take O(n^2) to generate groups and to check
against each group n iterations will be needed thus overall it takes O(n^3) time.
Efficient Approach: We can use the greedy approach. Sort the whole array and our result
is sum of last two elements minus sum of first two elements.
C++
PHP
<?php
// PHP program to find minimum
// difference between groups of
// highest and lowest sums.
function CalculateMax($arr, $n)
{
// Sorting the whole array.
sort($arr);
$min_sum = $arr[0] +
$arr[1];
1175
Chapter 176. Maximum difference between groups of size two
$max_sum = $arr[$n - 1] +
$arr[$n - 2];
return abs($max_sum -
$min_sum);
}
// Driver code
$arr = array (6, 7, 1, 11 );
$n = sizeof($arr);
echo CalculateMax($arr, $n), "\n" ;
// This code is contributed by ajit
?>
Output:
11
Source
https://www.geeksforgeeks.org/maximum-difference-groups-size-two/
1176
Chapter 177
Approach:
1. Get the index of the element which is making the array unsorted.
2. Get the maximum element from the second array satisfying the neighboring conditions
of the element with wrong index i.e
(i) max element >= arr[wrong index-1]
(ii)max element <= arr[wrong index+1] if wrong index+1 exists
1177
Chapter 177. Maximum in an array that can make another array sorted
// array sorted
bool swapElement(int arr1[], int arr2[], int n)
{
// wrongIdx is the index of the element
// which is making the first array unsorted
int wrongIdx = 0;
for (int i = 1; i < n; i++) {
if (arr1[i] < arr1[i - 1])
wrongIdx = i;
int maximum = INT_MIN;
int maxIdx = -1;
bool res = false;
// Find the maximum element which satisfies the
// the above mentioned neighboring conditions
for (int i = 0; i < n; i++) {
if (arr2[i] > maximum && arr2[i] >= arr1[wrongIdx - 1]) {
if (wrongIdx + 1 <= n - 1 &&
arr2[i] <= arr1[wrongIdx + 1]) {
maximum = arr2[i];
maxIdx = i;
res = true;
}
}
}
// if res is true then swap the element
// and make the first array sorted
if (res)
swap(arr1[wrongIdx], arr2[maxIdx]);
return res;
}
// Function to print the sorted array if elements
// are swapped.
void getSortedArray(int arr1[], int arr2[], int n)
{
if (swapElement(arr1, arr2, n))
for (int i = 0; i < n; i++)
cout << arr1[i] << " ";
else
cout << "Not Possible" << endl;
}
// Drivers code
1178
Chapter 177. Maximum in an array that can make another array sorted
int main()
{
int arr1[] = { 1, 3, 7, 4, 10 };
int arr2[] = { 2, 1, 6, 8, 9 };
int n = sizeof(arr1) / sizeof(arr1[0]);
getSortedArray(arr1, arr2, n);
}
Output:
1 3 7 9 10
Source
https://www.geeksforgeeks.org/maximum-in-an-array-that-can-make-another-array-sorted/
1179
Chapter 178
Maximum number of partitions that can be sorted individually to make sorted - Geeks-
forGeeks
Given an array arr[] of size n such that elements of arr[] in range [0, 1, ..n-1]. Our task is to
divide the array into maximum number of partitions that can be sorted individually, then
concatenated to make the whole array sorted.
Examples :
The idea is based on the fact that if an element arr[i] is maximum of prefix arr[0..i], then
we can make a partition ending with arr[i].
C++
1180
Chapter 178. Maximum number of partitions that can be sorted individually to make sorted
Java
1181
Chapter 178. Maximum number of partitions that can be sorted individually to make sorted
// If maximum so far is equal to index,
// we can make a new partition ending at
// index i.
if (max_so_far == i)
ans++;
}
return ans;
}
// Driver code
public static void main (String[] args)
{
int arr[] = { 1, 0, 2, 3, 4 };
int n = arr.length;
System.out.println (maxPartitions(arr, n));
}
}
// This code is contributed by vt_m.
Python3
1182
Chapter 178. Maximum number of partitions that can be sorted individually to make sorted
print(maxPartitions(arr, n))
# This code is contributed by Smitha Dinesh Semwal.
C#
PHP
<?php
// PHP program to find Maximum
1183
Chapter 178. Maximum number of partitions that can be sorted individually to make sorted
Output:
Source
https://www.geeksforgeeks.org/maximum-number-partitions-can-sorted-individually-make-sorted/
1184
Chapter 179
Before solving this question we have to take care of some given conditions and they are
listed as:
• While building up the subsets, take care that no subset should contain repetitive
elements. And for this we can conclude that all such elements whose frequency are
1185
Chapter 179. Maximum possible difference of two subsets of an array
2, going to be part of both subsets and hence overall they don’t have any impact on
difference of subset sum. So, we can easily ignore them.
• For making the difference of sum of elements of both subset maximum we have to make
subset in such a way that all positive elements belongs to one subset and negative ones
to other subset.
if isSingleOccurance == true
if (arr[i] > 0)
SubsetSum_1 += arr[i];
else
SubsetSum_2 += arr[i];
return abs(SubsetSum_1 - SubsetSum2)
C++
1186
Chapter 179. Maximum possible difference of two subsets of an array
arr[i] = arr[j] = 0;
break;
}
}
if (isSingleOccurance) {
if (arr[i] > 0)
SubsetSum_1 += arr[i];
else
SubsetSum_2 += arr[i];
}
}
return abs(SubsetSum_1 - SubsetSum_2);
}
// driver program
int main()
{
int arr[] = { 4, 2, -3, 3, -2, -2, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum Difference = " << maxDiff(arr, n);
return 0;
}
Java
1187
Chapter 179. Maximum possible difference of two subsets of an array
break;
}
}
if (isSingleOccurance)
{
if (arr[i] > 0)
SubsetSum_1 += arr[i];
else
SubsetSum_2 += arr[i];
}
}
return Math.abs(SubsetSum_1 - SubsetSum_2);
}
// driver program
static public void main (String[] args)
{
int []arr = { 4, 2, -3, 3, -2, -2, 8 };
int n = arr.length;
System.out.println("Maximum Difference = "
+ maxDiff(arr, n));
}
}
// This code is contributed by vt_m.
Python3
1188
Chapter 179. Maximum possible difference of two subsets of an array
isSingleOccurance = False
arr[i] = arr[j] = 0
break
if (isSingleOccurance == True) :
if (arr[i] > 0) :
SubsetSum_1 += arr[i]
else :
SubsetSum_2 += arr[i]
return abs(SubsetSum_1 - SubsetSum_2)
# Driver Code
arr = [4, 2, -3, 3, -2, -2, 8]
n = len(arr)
print ("Maximum Difference = {}"
. format(maxDiff(arr, n)))
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
1189
Chapter 179. Maximum possible difference of two subsets of an array
}
}
if (isSingleOccurance)
{
if (arr[i] > 0)
SubsetSum_1 += arr[i];
else
SubsetSum_2 += arr[i];
}
}
return Math.Abs(SubsetSum_1 - SubsetSum_2);
}
// driver program
static public void Main ()
{
int []arr = { 4, 2, -3, 3, -2, -2, 8 };
int n = arr.Length;
Console.WriteLine("Maximum Difference = "
+ maxDiff(arr, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP find maximum difference
// of subset sum
// function for maximum subset diff
function maxDiff($arr, $n)
{
$SubsetSum_1 = 0;
$SubsetSum_2 = 0;
for ($i = 0; $i <= $n - 1; $i++)
{
$isSingleOccurance = true;
for ($j = $i + 1; $j <= $n - 1; $j++)
{
// if frequency of any element is two
// make both equal to zero
if ($arr[$i] == $arr[$j])
1190
Chapter 179. Maximum possible difference of two subsets of an array
{
$isSingleOccurance = false;
$arr[$i] = $arr[$j] = 0;
break;
}
}
if ($isSingleOccurance)
{
if ($arr[$i] > 0)
$SubsetSum_1 += $arr[$i];
else
$SubsetSum_2 += $arr[$i];
}
}
return abs($SubsetSum_1 - $SubsetSum_2);
}
// Driver Code
$arr = array(4, 2, -3, 3, -2, -2, 8);
$n = sizeof($arr);
echo "Maximum Difference = " , maxDiff($arr, $n);
// This code is contributed by nitin mittal
?>
Output:
Maximum Difference = 20
1191
Chapter 179. Maximum possible difference of two subsets of an array
C++
Java
1192
Chapter 179. Maximum possible difference of two subsets of an array
// function for maximum subset diff
static int maxDiff(int []arr, int n)
{
int result = 0;
// sort the array
Arrays.sort(arr);
// calculate the result
for (int i = 0; i < n - 1; i++)
{
if (arr[i] != arr[i + 1])
result += Math.abs(arr[i]);
else
i++;
}
// check for last element
if (arr[n - 2] != arr[n - 1])
result += Math.abs(arr[n - 1]);
// return result
return result;
}
// driver program
static public void main (String[] args)
{
int[] arr = { 4, 2, -3, 3, -2, -2, 8 };
int n = arr.length;
System.out.println("Maximum Difference = "
+ maxDiff(arr, n));
}
}
// This code is contributed by vt_m.
C#
1193
Chapter 179. Maximum possible difference of two subsets of an array
PHP
<?php
// PHP find maximum difference of subset sum
// function for maximum subset diff
function maxDiff( $arr, $n)
{
$result = 0;
// sort the array
1194
Chapter 179. Maximum possible difference of two subsets of an array
sort($arr);
// calculate the result
for ( $i = 0; $i < $n - 1; $i++)
{
if ($arr[$i] != $arr[$i + 1])
$result += abs($arr[$i]);
else
$i++;
}
// check for last element
if ($arr[$n - 2] != $arr[$n - 1])
$result += abs($arr[$n - 1]);
// return result
return $result;
}
// Driver Code
$arr = array( 4, 2, -3, 3, -2, -2, 8 );
$n = count($arr);
echo "Maximum Difference = "
, maxDiff($arr, $n);
// This code is contributed by anuj_67.
?>
Output:
Maximum Difference = 20
1195
Chapter 179. Maximum possible difference of two subsets of an array
#include <bits/stdc++.h>
using namespace std;
// function for maximum subset diff
int maxDiff(int arr[], int n)
{
unordered_map<int, int> hashPositive;
unordered_map<int, int> hashNegative;
int SubsetSum_1 = 0, SubsetSum_2 = 0;
// construct hash for positive elements
for (int i = 0; i <= n - 1; i++)
if (arr[i] > 0)
hashPositive[arr[i]]++;
// calculate subset sum for positive elements
for (int i = 0; i <= n - 1; i++)
if (arr[i] > 0 && hashPositive[arr[i]] == 1)
SubsetSum_1 += arr[i];
// construct hash for negative elements
for (int i = 0; i <= n - 1; i++)
if (arr[i] < 0)
hashNegative[abs(arr[i])]++;
// calculate subset sum for negative elements
for (int i = 0; i <= n - 1; i++)
if (arr[i] < 0 &&
hashNegative[abs(arr[i])] == 1)
SubsetSum_2 += arr[i];
return abs(SubsetSum_1 - SubsetSum_2);
}
// driver program
int main()
{
int arr[] = { 4, 2, -3, 3, -2, -2, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum Difference = " << maxDiff(arr, n);
return 0;
}
Output:
Maximum Difference = 20
1196
Chapter 179. Maximum possible difference of two subsets of an array
Source
https://www.geeksforgeeks.org/maximum-possible-difference-two-subsets-array/
1197
Chapter 180
1198
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
Python3
1199
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
C#
// A C# program to find a
// maximum product of a
// triplet in array of integers
using System;
class GFG {
// Function to find a maximum
// product of a triplet in array
// of integers of size n
static int maxProduct(int []arr, int n)
{
// if size is less than
// 3, no triplet exists
if (n < 3)
return -1;
1200
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
PHP
<?php
// A PHP program to find a
// maximum product of a
// triplet in array of integers
// Function to find a maximum
// product of a triplet
// in array of integers of
// size n
function maxProduct($arr, $n)
{
$INT_MIN = 0;
// if size is less than
// 3, no triplet exists
if ($n < 3)
return -1;
1201
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
// will contain max product
$max_product = $INT_MIN;
for ($i = 0; $i < $n - 2; $i++)
for ($j = $i + 1; $j < $n - 1; $j++)
for ($k = $j + 1; $k < $n; $k++)
$max_product = max($max_product,
$arr[$i] * $arr[$j] * $arr[$k]);
return $max_product;
}
// Driver Code
$arr = array(10, 3, 5, 6, 20 );
$n = sizeof($arr);
$max = maxProduct($arr, $n);
if ($max == -1)
echo "No Triplet Exists";
else
echo "Maximum product is " ,$max;
// This code is contributed by nitin mittal.
?>
Output :
1. Construct four auxiliary arrays leftMax[], rightMax[], leftMin[] and rightMin[] of same
size as input array.
2. Fill leftMax[], rightMax[], leftMin[] and rightMin[] in below manner.
• leftMax[i] will contain maximum element on left of arr[i] excluding arr[i]. For
index 0, left will contain -1.
• leftMin[i] will contain minimum element on left of arr[i] excluding arr[i]. For
index 0, left will contain -1.
• rightMax[i] will contain maximum element on right of arr[i] excluding arr[i]. For
index n-1, right will contain -1.
• rightMin[i] will contain minimum element on right of arr[i] excluding arr[i]. For
index n-1, right will contain -1.
3. For all array indexes i except first and last index, compute maximum of arr[i]*x*y
where x can be leftMax[i] or leftMin[i] and y can be rightMax[i] or rightMin[i].
1202
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
1203
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
1204
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
if (max == -1)
cout << "No Triplet Exists";
else
cout << "Maximum product is " << max;
return 0;
}
Output :
1205
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
Output :
1. Scan the array and compute Maximum, second maximum and third maximum element
present in the array.
2. Scan the array and compute Minimum and second minimum element present in the
array.
3. Return the maximum of product of Maximum, second maximum and third maximum
and product of Minimum, second minimum and Maximum element.
Note – Step 1 and Step 2 can be done in single traversal of the array.
Below is its C++ implementation –
1206
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
1207
Chapter 180. Maximum product of a triplet (subsequnece of size 3) in array
Output :
Exercise:
1. Print the triplet that has maximum product.
2. Find a minimum product of a triplet in array.
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : shrikanth13, nitin mittal, vt_m, Rasheed60
Source
https://www.geeksforgeeks.org/find-maximum-product-of-a-triplet-in-array/
1208
Chapter 181
Maximum product of
subsequence of size k
Examples:
1209
Chapter 181. Maximum product of subsequence of size k
Now,
if A[0]*A[1] > A[n-1]*A[n-2],
second max product pair will be
either A[2]*A[3] OR A[n-1]*[n-2].
else second max product pair will be
either A[0]*A[1] OR A[n-3]*[n-4].
1210
Chapter 181. Maximum product of subsequence of size k
sort(A, A + n);
// variable to store final product of all element
// of sub-sequence of size k
int product = 1;
// CASE I
// If max element is 0 and
// k is odd then max product will be 0
if (A[n - 1] == 0 && (k & 1))
return 0;
// CASE II
// If all elements are negative and
// k is odd then max product will be
// product of rightmost-subarray of size k
if (A[n - 1] <= 0 && (k & 1)) {
for (int i = n - 1; i >= n - k; i--)
product *= A[i];
return product;
}
// else
// i is current left pointer index
int i = 0;
// j is current right pointer index
int j = n - 1;
// CASE III
// if k is odd and rightmost element in
// sorted array is positive then it
// must come in subsequnce
// Multiplying A[j] with product and
// correspondingly changing j
if (k & 1) {
product *= A[j];
j--;
k--;
}
// CASE IV
// Now k is even
// Now we deal with pairs
// Each time a pair is multiplied to product
// ie.. two elemnts are added to subsequence each time
// Effectively k becomes half
// Hence, k >>= 1 means k /= 2
1211
Chapter 181. Maximum product of subsequence of size k
k >>= 1;
// Now finding k corresponding pairs
// to get maximum possible value of product
for (int itr = 0; itr < k; itr++) {
// product from left pointers
int left_product = A[i] * A[i + 1];
// product from right pointers
int right_product = A[j] * A[j - 1];
// Taking the max product from two choices
// Correspondingly changing the pointer's position
if (left_product > right_product) {
product *= left_product;
i += 2;
}
else {
product *= right_product;
j -= 2;
}
}
// Finally return product
return product;
}
// Driver Code to test above function
int main()
{
int A[] = { 1, 2, -1, -3, -6, 4 };
int n = sizeof(A) / sizeof(A[0]);
int k = 4;
cout << maxProductSubarrayOfSizeK(A, n, k);
return 0;
}
Java
1212
Chapter 181. Maximum product of subsequence of size k
1213
Chapter 181. Maximum product of subsequence of size k
C#
1214
Chapter 181. Maximum product of subsequence of size k
using System;
class GFG {
// Function to find maximum possible product
static int maxProductSubarrayOfSizeK(int[] A, int n,
int k)
{
// sorting given input array
Array.Sort(A);
// variable to store final product of
// all element of sub-sequence of size k
int product = 1;
int i;
// CASE I
// If max element is 0 and
// k is odd then max product will be 0
if (A[n - 1] == 0 && k % 2 != 0)
return 0;
// CASE II
// If all elements are negative and
// k is odd then max product will be
// product of rightmost-subarray of size k
if (A[n - 1] <= 0 && k % 2 != 0) {
for (i = n - 1; i >= n - k; i--)
product *= A[i];
return product;
}
// else
// i is current left pointer index
i = 0;
// j is current right pointer index
int j = n - 1;
// CASE III
// if k is odd and rightmost element in
// sorted array is positive then it
// must come in subsequnce
// Multiplying A[j] with product and
// correspondingly changing j
if (k % 2 != 0) {
product *= A[j];
j--;
1215
Chapter 181. Maximum product of subsequence of size k
k--;
}
// CASE IV
// Now k is even
// Now we deal with pairs
// Each time a pair is multiplied to
// product i.e.. two elemnts are added to
// subsequence each time Effectively k becomes half
// Hence, k >>= 1 means k /= 2
k >>= 1;
// Now finding k corresponding pairs
// to get maximum possible value of product
for (int itr = 0; itr < k; itr++) {
// product from left pointers
int left_product = A[i] * A[i + 1];
// product from right pointers
int right_product = A[j] * A[j - 1];
// Taking the max product from two choices
// Correspondingly changing the pointer's position
if (left_product > right_product) {
product *= left_product;
i += 2;
}
else {
product *= right_product;
j -= 2;
}
}
// Finally return product
return product;
}
// driver program
public static void Main()
{
int[] A = { 1, 2, -1, -3, -6, 4 };
int n = A.Length;
int k = 4;
Console.WriteLine(maxProductSubarrayOfSizeK(A, n, k));
}
}
1216
Chapter 181. Maximum product of subsequence of size k
Output:
144
Time Complexity : O(n * log n) O(n * log n) from sorting + O(k) from one traversal
in array = O(n * log n)
Auxiliary Space : O(1)
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-product-subsequence-size-k/
1217
Chapter 182
Input : { 1, 2, 4, 8 }
Output : 18
Explanation : For the given array there are
several sequence possible
like : {2, 1, 4, 8}
{4, 2, 1, 8} and some more.
Now, the absolute difference of an array sequence will be
like for this array sequence {1, 2, 4, 8}, the absolute
difference sum is
= |1-2| + |2-4| + |4-8| + |8-1|
= 14
For the given array, we get the maximum value for
the sequence {1, 8, 2, 4}
= |1-8| + |8-2| + |2-4| + |4-1|
= 18
To solve this problem, we have to think greedily that how can we maximize the difference
value of the elements so that we can have a maximum sum. This is possible only if we
calculate the difference between some very high values and some very low values like (highest
– smallest). This is the idea which we have to use to solve this problem. Let us see the
above example, we will have maximum difference possible for sequence {1, 8, 2, 4} because
in this sequence we will get some high difference values, ( 1-8 = 7, 8-2 = 6 .. ). Here, by
1218
Chapter 182. Maximum sum of absolute difference of an array
placing 8(highest element) in place of 1 and 2 we get two high difference values. Similarly,
for the other values, we will place next highest values in between other, as we have only one
left i.e 4 which is placed at last.
Algorithm: To get the maximum sum, we should have a sequence in which small and large
elements comes alternate. This is done to get maximum difference.
For the implementation of the above algorithm ->
1. We will sort the array.
2. Calculate the final sequence by taking one smallest element and largest element from the
sorted array and make one vector array of this final sequence.
3. Finally, calculate the sum of absolute difference between the elements of the array.
Below is the implementation of above idea :
C++
// CPP implementation of
// above algorithm
#include <bits/stdc++.h>
using namespace std;
int MaxSumDifference(int a[], int n)
{
// final sequence stored in the vector
vector<int> finalSequence;
// sort the original array
// so that we can retrieve
// the large elements from
// the end of array elements
sort(a, a + n);
// In this loop first we will insert
// one smallest element not entered
// till that time in final sequence
// and then enter a highest element
// (not entered till that time) in
// final sequence so that we
// have large difference value. This
// process is repeated till all array
// has completely entered in sequence.
// Here, we have loop till n/2 because
// we are inserting two elements at a
// time in loop.
for (int i = 0; i < n / 2; ++i) {
finalSequence.push_back(a[i]);
finalSequence.push_back(a[n - i - 1]);
}
1219
Chapter 182. Maximum sum of absolute difference of an array
Java
// Java implementation of
// above algorithm
import java.io.*;
import java.util.*;
public class GFG {
static int MaxSumDifference(Integer []a, int n)
{
// final sequence stored in the vector
List<Integer> finalSequence =
new ArrayList<Integer>();
// sort the original array
1220
Chapter 182. Maximum sum of absolute difference of an array
1221
Chapter 182. Maximum sum of absolute difference of an array
{
Integer []a = { 1, 2, 4, 8 };
int n = a.length;
System.out.print(MaxSumDifference(a, n));
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
import numpy as np
class GFG:
def MaxSumDifference(a,n):
# sort the original array
# so that we can retrieve
# the large elements from
# the end of array elements
np.sort(a);
# In this loop first we will
# insert one smallest element
# not entered till that time
# in final sequence and then
# enter a highest element(not
# entered till that time) in
# final sequence so that we
# have large difference value.
# This process is repeated till
# all array has completely
# entered in sequence. Here,
# we have loop till n/2 because
# we are inserting two elements
# at a time in loop.
j = 0
finalSequence = [0 for x in range(n)]
for i in range(0, int(n / 2)):
finalSequence[j] = a[i]
finalSequence[j + 1] = a[n - i - 1]
j = j + 2
# variable to store the
# maximum sum of absolute
# difference
MaximumSum = 0
1222
Chapter 182. Maximum sum of absolute difference of an array
# In this loop absolute
# difference of elements
# for the final sequence
# is calculated.
for i in range(0, n - 1):
MaximumSum = (MaximumSum +
abs(finalSequence[i] -
finalSequence[i + 1]))
# absolute difference of last
# element and 1st element
MaximumSum = (MaximumSum +
abs(finalSequence[n - 1] -
finalSequence[0]));
# return the value
print (MaximumSum)
# Driver Code
a = [ 1, 2, 4, 8 ]
n = len(a)
GFG.MaxSumDifference(a, n);
# This code is contributed
# by Prateek Bajaj
C#
// C# implementation of
// above algorithm
using System;
using System.Collections.Generic;
class GFG {
static int MaxSumDifference(int []a, int n)
{
// final sequence stored in the vector
List<int> finalSequence = new List<int>();
// sort the original array
// so that we can retrieve
// the large elements from
// the end of array elements
Array.Sort(a);
// In this loop first we will insert
1223
Chapter 182. Maximum sum of absolute difference of an array
1224
Chapter 182. Maximum sum of absolute difference of an array
Output :
18
Source
https://www.geeksforgeeks.org/maximum-sum-absolute-difference-array/
1225
Chapter 183
1226
Chapter 183. Maximum sum of pairwise product in an array with negative allowed
1227
Chapter 183. Maximum sum of pairwise product in an array with negative allowed
return sum;
}
// Drivers code
int main()
{
int arr[] = { -1, 9, 4, 5, -4, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findSum(arr, n);
return 0;
}
Java
1228
Chapter 183. Maximum sum of pairwise product in an array with negative allowed
Python3
1229
Chapter 183. Maximum sum of pairwise product in an array with negative allowed
i += 2
else:
break
# Second multiply positive numbers
# pairwise and summed up from the
# last as to get maximum sum.
j = n - 1
while j >= 0 and arr[j] > 0:
if j != 0 and arr[j - 1] > 0:
sum = (sum + (arr[j] * arr[j - 1])
% Mod) % Mod
j -= 2
else:
break
# To handle case if positive
# and negative numbers both
# are odd in counts.
if j > i:
sum = (sum + (arr[i] * arr[j]) % Mod)
% Mod
# If one of them occurs odd times
elif i == j:
sum = (sum + arr[i]) % Mod
return sum
# Driver code
arr = [ -1, 9, 4, 5, -4, 7 ]
n = len(arr)
print(findSum(arr, n))
# This code is contributed by "Sharad_Bhardwaj".
C#
1230
Chapter 183. Maximum sum of pairwise product in an array with negative allowed
long sum = 0;
// Sort the array first
Array.Sort(arr);
// First multiply negative numbers
// pairwise and sum up from starting
// as to get maximum sum.
int i = 0;
while (i < n && arr[i] < 0) {
if (i != n - 1 && arr[i + 1] <= 0) {
sum = (sum + (arr[i] * arr[i + 1]) % Mod) % Mod;
i += 2;
}
else
break;
}
// Second multiply positive numbers
// pairwise and summed up from the
// last as to get maximum sum.
int j = n - 1;
while (j >= 0 && arr[j] > 0) {
if (j != 0 && arr[j - 1] > 0) {
sum = (sum + (arr[j] * arr[j - 1]) % Mod) % Mod;
j -= 2;
}
else
break;
}
// To handle case if positive and negative
// numbers both are odd in counts.
if (j > i)
sum = (sum + (arr[i] * arr[j]) % Mod) % Mod;
// If one of them occurs odd times
else if (i == j)
sum = (sum + arr[i]) % Mod;
return sum;
}
// Drivers code
public static void Main()
{
int[] arr = { -1, 9, 4, 5, -4, 7 };
int n = arr.Length;
1231
Chapter 183. Maximum sum of pairwise product in an array with negative allowed
Console.WriteLine(findSum(arr, n));
}
}
/*This code is contributed by vt_m.*/
Output:
87
Source
https://www.geeksforgeeks.org/maximum-sum-of-pairwise-product-in-an-array-with-negative-allowed/
1232
Chapter 184
Naive approach : In this method we simply run three loop and one by one add three
element and compare with previous sum if the sum of three element is greater then store in
previous sum .
C++
1233
Chapter 184. Maximum triplet sum in array
Java
Python3
1234
Chapter 184. Maximum triplet sum in array
C#
1235
Chapter 184. Maximum triplet sum in array
int n = arr.Length;
Console.WriteLine(maxTripletSum(arr, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP code to find maximum triplet sum
function maxTripletSum( $arr, $n)
{
// Initialize sum with INT_MIN
$sum = PHP_INT_MIN;
for($i = 0; $i < $n; $i++)
for($j = $i + 1; $j < $n; $j++)
for($k = $j + 1; $k < $n; $k++)
if ($sum < $arr[$i] +
$arr[$j] +
$arr[$k])
$sum = $arr[$i] +
$arr[$j] +
$arr[$k];
return $sum;
}
// Driver Code
$arr = array(1, 0, 8, 6, 4, 2);
$n = count($arr);
echo maxTripletSum($arr, $n);
// This code is contributed by anuj_67.
?>
Output :
18
1236
Chapter 184. Maximum triplet sum in array
Another approach : In this, we first need to sort the whole array and after that when we
add last three element of the array then we find maximum sum of triplates.
C++
Java
1237
Chapter 184. Maximum triplet sum in array
Python3
C#
1238
Chapter 184. Maximum triplet sum in array
class GFG {
// This function assumes that there are
// at least three elements in arr[].
static int maxTripletSum(int[] arr, int n)
{
// sort the given array
Array.Sort(arr);
// After sorting the array.
// Add last three element
// of the given array
return arr[n - 1] + arr[n - 2] + arr[n - 3];
}
// Driven code
public static void Main()
{
int[] arr = { 1, 0, 8, 6, 4, 2 };
int n = arr.Length;
Console.WriteLine(maxTripletSum(arr, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP code to find
// maximum triplet sum
// This function assumes that
// there are at least
// three elements in arr[].
function maxTripletSum( $arr, $n)
{
// sort the given array
sort($arr);
// After sorting the array.
// Add last three element
// of the given array
return $arr[$n - 1] + $arr[$n - 2] +
$arr[$n - 3];
}
1239
Chapter 184. Maximum triplet sum in array
// Driver code
$arr = array( 1, 0, 8, 6, 4, 2 );
$n = count($arr);
echo maxTripletSum($arr, $n);
// This code is contributed by anuj_67.
?>
Output :
18
1240
Chapter 184. Maximum triplet sum in array
maxB = arr[i];
}
// Update third maximum element
else if (arr[i] > maxC)
maxC = arr[i];
}
return (maxA + maxB + maxC);
}
// Driven code
int main()
{
int arr[] = { 1, 0, 8, 6, 4, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << maxTripletSum(arr, n);
return 0;
}
Java
1241
Chapter 184. Maximum triplet sum in array
// Update second maximum and third maximum
// element
else if (arr[i] > maxB)
{
maxC = maxB;
maxB = arr[i];
}
// Update third maximum element
else if (arr[i] > maxC)
maxC = arr[i];
}
return (maxA + maxB + maxC);
}
// Driven code
public static void main(String args[])
{
int arr[] = { 1, 0, 8, 6, 4, 2 };
int n = arr.length;
System.out.println(maxTripletSum(arr, n));
}
}
// This code is contributed by Nikita Tiwari.
Python3
1242
Chapter 184. Maximum triplet sum in array
C#
1243
Chapter 184. Maximum triplet sum in array
maxC = maxB;
maxB = maxA;
maxA = arr[i];
}
// Update second maximum and third
// maximum element
else if (arr[i] > maxB) {
maxC = maxB;
maxB = arr[i];
}
// Update third maximum element
else if (arr[i] > maxC)
maxC = arr[i];
}
return (maxA + maxB + maxC);
}
// Driven code
public static void Main()
{
int[] arr = { 1, 0, 8, 6, 4, 2 };
int n = arr.Length;
Console.WriteLine(maxTripletSum(arr, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP code to find
// maximum triplet sum
// This function assumes that
// there are at least three
// elements in arr[].
function maxTripletSum($arr, $n)
{
// Initialize Maximum,
// second maximum and
// third maximum element
$maxA = PHP_INT_MIN;
$maxB = PHP_INT_MIN;
$maxC = PHP_INT_MIN;
1244
Chapter 184. Maximum triplet sum in array
for ( $i = 0; $i < $n; $i++)
{
// Update Maximum,
// second maximum and
// third maximum element
if ($arr[$i] > $maxA)
{
$maxC = $maxB;
$maxB = $maxA;
$maxA = $arr[$i];
}
// Update second maximum and
// third maximum element
else if ($arr[$i] > $maxB)
{
$maxC = $maxB;
$maxB = $arr[$i];
}
// Update third maximum element
else if ($arr[$i] > $maxC)
$maxC = $arr[$i];
}
return ($maxA + $maxB + $maxC);
}
// Driven code
$arr = array( 1, 0, 8, 6, 4, 2 );
$n = count($arr);
echo maxTripletSum($arr, $n);
// This code is contributed by anuj_67.
?>
Output :
18
1245
Chapter 184. Maximum triplet sum in array
Source
https://www.geeksforgeeks.org/maximum-triplet-sum-array/
1246
Chapter 185
k < n
n + k is always odd.
Examples :
Input : arr[] = { 4, 7 }
k = 1
Output : 7
Explanation : One of the possible solutions
is to add 8 making the array [4, 7, 8], whose
median is 7
Input : arr[] = { 6, 1, 1, 1, 1 }
k = 2
Output : 1
Explanation : No matter what elements we add
to this array, the median will always be 1
We first sort the array in increasing order. Since value of k is less than n and n+k is always
odd, we can always choose to add k elements which are greater than the largest element of
array and (n+k)/2th element is always a median of the array.
C++
1247
Chapter 185. Median after K additional integers
Java
1248
Chapter 185. Median after K additional integers
Python3
C#
1249
Chapter 185. Median after K additional integers
PHP
<?php
// PHP program to find median
// of an array when we are allowed
// to add additional K integers to it.
// Find median of array
// after adding k elements
function printMedian($arr, $n, $K)
{
// sorting the array
// in increasing order.
sort($arr);
// printing the median of
1250
Chapter 185. Median after K additional integers
Output :
Improved By : Sam007
Source
https://www.geeksforgeeks.org/median-k-additional-integers/
1251
Chapter 186
Prerequisites: Count Sort, Median of Array, Mode (Most frequent element in array)
1. Auxiliary(count) array before summing its previous counts, c[]:
Index: 0 1 2 3 4 5 6 7 8 9 10
count: 0 4 1 0 0 0 0 1 0 0 0
2. Mode = index with maximum value of count.
Mode = 1(for above example)
3. count array is modified similarly as it is done while performing count sort.
Index: 0 1 2 3 4 5 6 7 8 9 10
count: 0 3 5 6 7 8 9 10 10 10 10
4. output array is calculated normally as in count sort, b[]:
output array b[] = {1, 1, 1, 2, 2, 3, 4, 5, 6, 7}
1252
Chapter 186. Median and Mode using Counting Sort
Source
https://www.geeksforgeeks.org/median-and-mode-using-counting-sort/
1253
Chapter 187
Input : A = [1, 2, 3, 4, 5]
B = [2, 3, 4]
C = [4, 5, 6, 7]
Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7]
Input : A = [1, 2, 3, 5]
B = [6, 7, 8, 9 ]
C = [10, 11, 12]
Output: D = [1, 2, 3, 5, 6, 7, 8, 9. 10, 11, 12]
function merge(A, B)
Let m and n be the sizes of A and B
1254
Chapter 187. Merge 3 Sorted Arrays
Return D
function merge_three(A, B, C)
T = merge(A, B)
return merge(T, C)
1255
Chapter 187. Merge 3 Sorted Arrays
Python
1256
Chapter 187. Merge 3 Sorted Arrays
d = []
# Merge from a and b together
while i < m and j < n:
if a[i] <= b[j]:
d.append(a[i])
i += 1
else:
d.append(b[j])
j += 1
# Merge from a if b has run out
while i < m:
d.append(a[i])
i += 1
# Merge from b if a has run out
while j < n:
d.append(b[j])
j += 1
return d
def merge(a, b, c):
t = merge_two(a, b)
return merge_two(t, c)
if __name__ == "__main__":
A = [1, 2, 3, 5]
B = [6, 7, 8, 9]
C = [10, 11, 12]
print(merge(A, B, C))
Output:
function merge-three(A, B, C)
Let m, n, o be size of A, B, and C
Let D be the array to store the result
1257
Chapter 187. Merge 3 Sorted Arrays
return D
Complexity: The Time Complexity is O(m+n+o) since we process each element from the
three arrays once. We only need one array to store the result of merging and so ignoring
this array, the space complexity is O(1).
The C++ and Python Implementation of the algorithm is given below:
C++
1258
Chapter 187. Merge 3 Sorted Arrays
1259
Chapter 187. Merge 3 Sorted Arrays
D.push_back(B[j]);
j++;
}
}
// B has exhausted
while (i < m && k < 0) {
if (A[i] <= C[j]) {
D.push_back(A[i]);
i++;
}
else {
D.push_back(C[j]);
k++;
}
}
// A has exhausted
while (j < n && k < 0) {
if (B[j] <= C[k]) {
D.push_back(B[j]);
j++;
}
else {
D.push_back(C[j]);
k++;
}
}
// A and B have exhausted
while (k < o)
D.push_back(C[k++]);
// B and C have exhausted
while (i < m)
D.push_back(A[i++]);
// A and C have exhausted
while (j < n)
D.push_back(B[j++]);
return D;
}
int main()
{
Vector A = { 1, 2, 41, 52, 84 };
Vector B = { 1, 2, 41, 52, 67 };
1260
Chapter 187. Merge 3 Sorted Arrays
Python
1261
Chapter 187. Merge 3 Sorted Arrays
d.append(b[j])
j += 1
else:
d.append(c[k])
k += 1
# Merge a and c if b has exhausted
while i < m and k < o:
if a[i] <= c[k]:
d.append(a[i])
i += 1
else:
d.append(c[k])
k += 1
# Take elements from a if b and c
# have exhausted
while i < m:
d.append(a[i])
i += 1
# Take elements from b if a and c
# have exhausted
while j < n:
d.append(b[j])
j += 1
# Take elements from c if a and
# b have exhausted
while k < o:
d.append(c[k])
k += 1
return d
if __name__ == "__main__":
a = [1, 2, 41, 52, 84]
b = [1, 2, 41, 52, 67]
c = [1, 2, 41, 52, 67, 85]
print(merge_three(a, b, c))
Output
[1, 1, 1, 2, 2, 2, 41, 41, 41, 52, 52, 52, 67, 67, 84, 85]
Note: While it is relatively easy to implement direct procedures to merge two or three
1262
Chapter 187. Merge 3 Sorted Arrays
arrays, the process becomes cumbersome if we want to merge 4 or more arrays. In such
cases, we should follow the procedure shown in Merge K Sorted Arrays.
Source
https://www.geeksforgeeks.org/merge-3-sorted-arrays/
1263
Chapter 188
Merge Sort
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
The following diagram from wikipedia shows the complete merge sort process for an example
array {38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that
the array is recursively divided in two halves till the size becomes 1. Once the size becomes
1, the merge processes comes into action and starts merging arrays back till the complete
array is merged.
1264
Chapter 188. Merge Sort
C/C++
1265
Chapter 188. Merge Sort
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
1266
Chapter 188. Merge Sort
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
1267
Chapter 188. Merge Sort
Java
1268
Chapter 188. Merge Sort
1269
Chapter 188. Merge Sort
System.out.println("Given Array");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.length-1);
System.out.println("\nSorted array");
printArray(arr);
}
}
/* This code is contributed by Rajat Mishra */
Python
1270
Chapter 188. Merge Sort
C#
1271
Chapter 188. Merge Sort
class MergeSort {
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int[] arr, int l,
int m, int r)
{
// Find sizes of two subarrays
// to be merged
int n1 = m - l + 1;
int n2 = r - m;
// Create temp arrays
int[] L = new int [n1];
int[] R = new int [n2];
// Copy data to temp arrays
int i, j;
for (i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (j = 0; j < n2; ++j)
R[j] = arr[m + 1+ j];
// Merge the temp arrays
// Initial indexes of first
// and second subarrays
i = 0;
j = 0;
// Initial index of merged
// subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
1272
Chapter 188. Merge Sort
j++;
}
k++;
}
// Copy remaining elements
// of L[] if any
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
// Copy remaining elements
// of R[] if any
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts
// arr[l..r] using merge()
void sort(int[] arr, int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l + r) / 2;
// Sort first and
// second halves
sort(arr, l, m);
sort(arr , m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
// A utility function to print
// array of size n
static void printArray(int[] arr)
{
int n = arr.Length;
1273
Chapter 188. Merge Sort
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.Write("\n");
}
// Driver Code
public static void Main()
{
int[] arr = {12, 11, 13, 5, 6, 7};
Console.Write("Given Array\n");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.Length - 1);
Console.Write("\nSorted array\n");
printArray(arr);
}
}
// This code is contributed by ChitraNayal.
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algo-
rithm and time complexity can be expressed as following recurrence relation.
T(n) = 2T(n/2) +
The above recurrence can be solved either using Recurrence Tree method or Master method.
1274
Chapter 188. Merge Sort
1. Merge Sort is useful for sorting linked lists in O(nLogn) time.In case of linked lists the
case is different mainly due to difference in memory allocation of arrays and linked
lists. Unlike arrays, linked list nodes may not be adjacent in memory. Unlike array,
in linked list, we can insert items in the middle in O(1) extra space and O(1) time.
Therefore merge operation of merge sort can be implemented without extra space for
linked lists.
In arrays, we can do random access as elements are continuous in memory. Let us say
we have an integer (4-byte) array A and let the address of A[0] be x then to access
A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can not do
random access in linked list. Quick Sort requires a lot of this kind of access. In linked
list to access i’th index, we have to travel each and every node from the head to i’th
node as we don’t have continuous block of memory. Therefore, the overhead increases
for quick sort. Merge sort accesses data sequentially and the need of random access is
low.
2. Inversion Count Problem
3. Used in External Sorting
Snapshots:
1275
Chapter 188. Merge Sort
1276
Chapter 188. Merge Sort
Improved By : ChitraNayal
Source
https://www.geeksforgeeks.org/merge-sort/
1277
Chapter 189
Merge sort for singly linked list is already discussed. The important change here is to modify
the previous pointers also when merging two lists.
Below is the implementation of merge sort for doubly linked list.
C
1278
Chapter 189. Merge Sort for Doubly Linked List
{
// If first linked list is empty
if (!first)
return second;
// If second linked list is empty
if (!second)
return first;
// Pick the smaller value
if (first->data < second->data)
{
first->next = merge(first->next,second);
first->next->prev = first;
first->prev = NULL;
return first;
}
else
{
second->next = merge(first,second->next);
second->next->prev = second;
second->prev = NULL;
return second;
}
}
// Function to do merge sort
struct Node *mergeSort(struct Node *head)
{
if (!head || !head->next)
return head;
struct Node *second = split(head);
// Recur for left and right halves
head = mergeSort(head);
second = mergeSort(second);
// Merge the two sorted halves
return merge(head,second);
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node **head, int data)
{
struct Node *temp =
(struct Node *)malloc(sizeof(struct Node));
temp->data = data;
1279
Chapter 189. Merge Sort for Doubly Linked List
1280
Chapter 189. Merge Sort for Doubly Linked List
}
struct Node *temp = slow->next;
slow->next = NULL;
return temp;
}
// Driver program
int main(void)
{
struct Node *head = NULL;
insert(&head,5);
insert(&head,20);
insert(&head,4);
insert(&head,3);
insert(&head,30);
insert(&head,10);
head = mergeSort(head);
printf("\n\nLinked List after sorting\n");
print(head);
return 0;
}
Java
1281
Chapter 189. Merge Sort for Doubly Linked List
1282
Chapter 189. Merge Sort for Doubly Linked List
}
// Pick the smaller value
if (first.data < second.data) {
first.next = merge(first.next, second);
first.next.prev = first;
first.prev = null;
return first;
} else {
second.next = merge(first, second.next);
second.next.prev = second;
second.prev = null;
return second;
}
}
// Driver program to test above functions
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(10);
list.head.next = new Node(30);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(20);
list.head.next.next.next.next.next = new Node(5);
Node node = null;
node = list.mergeSort(head);
System.out.println("Linked list after sorting :");
list.print(node);
}
}
// This code has been contributed by Mayank Jaiswal
Python
1283
Chapter 189. Merge Sort for Doubly Linked List
self.next = None
self.prev = None
class DoublyLinkedList:
# Constructor for empty Doubly Linked List
def __init__(self):
self.head = None
# Function to merge two linked list
def merge(self, first, second):
# If first linked list is empty
if first is None:
return second
# If secon linked list is empty
if second is None:
return first
# Pick the smaller value
if first.data < second.data:
first.next = self.merge(first.next, second)
first.next.prev = first
first.prev = None
return first
else:
second.next = self.merge(first, second.next)
second.next.prev = second
second.prev = None
return second
# Function to do merge sort
def mergeSort(self, tempHead):
if tempHead is None:
return tempHead
if tempHead.next is None:
return tempHead
second = self.split(tempHead)
# Recur for left and righ halves
tempHead = self.mergeSort(tempHead)
second = self.mergeSort(second)
# Merge the two sorted halves
return self.merge(tempHead, second)
1284
Chapter 189. Merge Sort for Doubly Linked List
# Split the doubly linked list (DLL) into two DLLs
# of half sizes
def split(self, tempHead):
fast = slow = tempHead
while(True):
if fast.next is None:
break
if fast.next.next is None:
break
fast = fast.next.next
slow = slow.next
temp = slow.next
slow.next = None
return temp
# Given a reference to the head of a list and an
# integer,inserts a new node on the front of list
def push(self, new_data):
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
# 3. Make next of new node as head and
# previous as None (already None)
new_node.next = self.head
# 4. change prev of head node to new_node
if self.head is not None:
self.head.prev = new_node
# 5. move the head to point to the new node
self.head = new_node
def printList(self, node):
temp = node
print "Forward Traversal using next poitner"
while(node is not None):
print node.data,
temp = node
node = node.next
print "\nBackward Traversal using prev pointer"
while(temp):
print temp.data,
temp = temp.prev
1285
Chapter 189. Merge Sort for Doubly Linked List
# Driver program to test the above functions
dll = DoublyLinkedList()
dll.push(5)
dll.push(20);
dll.push(4);
dll.push(3);
dll.push(30)
dll.push(10);
dll.head = dll.mergeSort(dll.head)
print "Linked List after sorting"
dll.printList(dll.head)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Source
https://www.geeksforgeeks.org/merge-sort-for-doubly-linked-list/
1286
Chapter 190
MergeSort(headRef)
1) If head is NULL or there is only one element in the Linked List
then return.
2) Else divide the linked list into two halves.
FrontBackSplit(head, &a, &b); /* a and b are two halves */
3) Sort the two halves a and b.
MergeSort(a);
MergeSort(b);
4) Merge the sorted a and b (using SortedMerge() discussed here)
and update the head pointer using headRef.
*headRef = SortedMerge(a, b);
1287
Chapter 190. Merge Sort for Linked Lists
{
int data;
struct Node* next;
};
/* function prototypes */
struct Node* SortedMerge(struct Node* a, struct Node* b);
void FrontBackSplit(struct Node* source,
struct Node** frontRef, struct Node** backRef);
/* sorts the linked list by changing next pointers (not data) */
void MergeSort(struct Node** headRef)
{
struct Node* head = *headRef;
struct Node* a;
struct Node* b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL))
{
return;
}
/* Split head into 'a' and 'b' sublists */
FrontBackSplit(head, &a, &b);
/* Recursively sort the sublists */
MergeSort(&a);
MergeSort(&b);
/* answer = merge the two sorted lists together */
*headRef = SortedMerge(a, b);
}
/* See https://www.geeksforgeeks.org/?p=3622 for details of this
function */
struct Node* SortedMerge(struct Node* a, struct Node* b)
{
struct Node* result = NULL;
/* Base cases */
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
/* Pick either a or b, and recur */
if (a->data <= b->data)
1288
Chapter 190. Merge Sort for Linked Lists
{
result = a;
result->next = SortedMerge(a->next, b);
}
else
{
result = b;
result->next = SortedMerge(a, b->next);
}
return(result);
}
/* UTILITY FUNCTIONS */
/* Split the nodes of the given list into front and back halves,
and return the two lists using the reference parameters.
If the length is odd, the extra node should go in the front list.
Uses the fast/slow pointer strategy. */
void FrontBackSplit(struct Node* source,
struct Node** frontRef, struct Node** backRef)
{
struct Node* fast;
struct Node* slow;
slow = source;
fast = source->next;
/* Advance 'fast' two nodes, and advance 'slow' one node */
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
/* 'slow' is before the midpoint in the list, so split it in two
at that point. */
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while(node!=NULL)
{
1289
Chapter 190. Merge Sort for Linked Lists
1290
Chapter 190. Merge Sort for Linked Lists
Java
1291
Chapter 190. Merge Sort for Linked Lists
{
return h;
}
// get the middle of the list
node middle = getMiddle(h);
node nextofmiddle = middle.next;
// set the next of middle node to null
middle.next = null;
// Apply mergeSort on left list
node left = mergeSort(h);
// Apply mergeSort on right list
node right = mergeSort(nextofmiddle);
// Merge the left and right lists
node sortedlist = sortedMerge(left, right);
return sortedlist;
}
// Utility function to get the middle of the linked list
node getMiddle(node h)
{
//Base case
if (h == null)
return h;
node fastptr = h.next;
node slowptr = h;
// Move fastptr by two and slow ptr by one
// Finally slowptr will point to middle node
while (fastptr != null)
{
fastptr = fastptr.next;
if(fastptr!=null)
{
slowptr = slowptr.next;
fastptr=fastptr.next;
}
}
return slowptr;
}
void push(int new_data)
{
/* allocate node */
1292
Chapter 190. Merge Sort for Linked Lists
1293
Chapter 190. Merge Sort for Linked Lists
http://cslibrary.stanford.edu/105/LinkedListProblems.pdf
Source
https://www.geeksforgeeks.org/merge-sort-for-linked-list/
1294
Chapter 191
<script>
// Create Node of LinkedList
function Node(data) {
this.node = data;
this.next = null;
}
// To initialize a linkedlist
function LinkedList(list) {
this.head = list || null
}
// Function to insert The new Node into the linkedList
1295
Chapter 191. Merge Sort for Linked Lists in JavaScript
LinkedList.prototype.insert = function(data) {
// Check if the linked list is empty
// so insert first node and lead head
// points to generic node
if (this.head === null)
this.head = new Node(data);
else {
// If linked list is not empty, insert the node
// at the end of the linked list
let list = this.head;
while (list.next) {
list = list.next;
}
// Now here list pointer points to last
// node let’s insert out new node in it
list.next = new Node(data)
}
}
// Function to print linkedList
LinkedList.prototype.iterate = function() {
// First we will check whether out
// linked list is empty or node
if (this.head === null)
return null;
// If linked list is not empty we will
// iterate from each Node and prints
// it’s value store in “data” property
let list = this.head;
// we will iterate until our list variable
// contains the “Next” value of the last Node
// i.e-> null
while (list) {
document.write(list.node)
if (list.next)
document.write(' -> ')
list = list.next
}
}
1296
Chapter 191. Merge Sort for Linked Lists in JavaScript
1297
Chapter 191. Merge Sort for Linked Lists in JavaScript
1298
Chapter 191. Merge Sort for Linked Lists in JavaScript
l.insert(3)
l.insert(2)
l.insert(1)
// Print the linked list
l.iterate()
// Sort the linked list
l.head = LinkedList.prototype.mergeSort(l.head)
document.write('<br> After sorting : ');
// Print the sorted linked list
l.iterate()
</script>
Output
Source
https://www.geeksforgeeks.org/merge-sort-linked-lists-javascript/
1299
Chapter 192
Input : 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
62, 27, 90, 59, 63, 26, 40, 26, 72, 36
Output : 15, 21, 26, 26, 27, 35, 36, 40, 49, 59,
62, 63, 72, 77, 83, 86, 86, 90, 92, 93
Input : 6, 5, 4, 3, 2, 1
Output : 1, 2, 3, 4, 5, 6
1300
Chapter 192. Merge Sort using Multi-threading
1301
Chapter 192. Merge Sort using Multi-threading
1302
Chapter 192. Merge Sort using Multi-threading
int main()
{
// generating random values in array
for (int i = 0; i < MAX; i++)
a[i] = rand() % 100;
// t1 and t2 for calculating time for
// merge sort
clock_t t1, t2;
t1 = clock();
pthread_t threads[THREAD_MAX];
// creating 4 threads
for (int i = 0; i < THREAD_MAX; i++)
pthread_create(&threads[i], NULL, merge_sort,
(void*)NULL);
// joining all 4 threads
for (int i = 0; i < 4; i++)
pthread_join(threads[i], NULL);
// merging the final 4 parts
merge(0, (MAX / 2 - 1) / 2, MAX / 2 - 1);
merge(MAX / 2, MAX/2 + (MAX-1-MAX/2)/2, MAX - 1);
merge(0, (MAX - 1)/2, MAX - 1);
t2 = clock();
// displaying sorted array
cout << "Sorted array: ";
for (int i = 0; i < MAX; i++)
cout << a[i] << " ";
// time taken by merge sort in seconds
cout << "Time taken: " << (t2 - t1) /
(double)CLOCKS_PER_SEC << endl;
return 0;
}</div>
Output:
Sorted array: 15 21 26 26 27 35 36 40 49 59 62 63 72 77 83 86 86 90 92 93
Time taken: 0.001023
1303
Chapter 192. Merge Sort using Multi-threading
Source
https://www.geeksforgeeks.org/merge-sort-using-multi-threading/
1304
Chapter 193
Merge Sort with O(1) extra space merge and O(n lg n) time - GeeksforGeeks
We have discussed Merge sort. How to modify the algorithm so that merge works in O(1)
extra space and algorithm still works in O(n Log n) time. We may assume that the input
values are integers only.
Examples:
Input : 5 4 3 2 1
Output : 1 2 3 4 5
For integer types, merge sort can be made inplace using some mathematics trick of modulus
and division. That means storing two elements value at one index and can be extracted
using modulus and division.
First we have to find a value greater than all the elements of the array. Now we can store
the original value as modulus and the second value as division. Suppose we want to store
arr[i] and arr[j] both at index i(means in arr[i]). First we have to find a ‘maxval’ greater
than both arr[i] and arr[j]. Now we can store as arr[i] = arr[i] + arr[j]*maxval. Now
arr[i]%maxval will give the original value of arr[i] and arr[i]/maxval will give the value
of arr[j]. So below is the implementation on merge sort.
C++
1305
Chapter 193. Merge Sort with O(1) extra space merge and O(n lg n) time
1306
Chapter 193. Merge Sort with O(1) extra space merge and O(n lg n) time
{
int maxele = *max_element(arr, arr+n) + 1;
mergeSortRec(arr, 0, n-1, maxele);
}
int main()
{
int arr[] = { 999, 612, 589, 856, 56, 945, 243 };
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, n);
cout << "Sorted array \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
C#
1307
Chapter 193. Merge Sort with O(1) extra space merge and O(n lg n) time
arr[k] = arr[k] +
(arr[j] % maxele) *
maxele;
k++;
j++;
}
}
while (i <= mid)
{
arr[k] = arr[k] + (arr[i] %
maxele) * maxele;
k++;
i++;
}
while (j <= end)
{
arr[k] = arr[k] + (arr[j] %
maxele) * maxele;
k++;
j++;
}
// Obtaining actual values
for ( i = beg; i <= end; i++)
arr[i] = arr[i] / maxele;
}
// Recursive merge sort
// with extra parameter, naxele
static void mergeSortRec(int []arr, int beg,
int end, int maxele)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSortRec(arr, beg,
mid, maxele);
mergeSortRec(arr, mid + 1,
end, maxele);
merge(arr, beg, mid,
end, maxele);
}
}
// This functions finds
// max element and calls
// recursive merge sort.
static void mergeSort(int []arr, int n)
1308
Chapter 193. Merge Sort with O(1) extra space merge and O(n lg n) time
{
int maxele = arr.Max() + 1;
mergeSortRec(arr, 0, n - 1, maxele);
}
//Driver code
public static void Main ()
{
int []arr = {999, 612, 589,
856, 56, 945, 243};
int n = arr.Length;
mergeSort(arr, n);
Console.WriteLine("Sorted array ");
for (int i = 0; i < n; i++)
Console.Write( arr[i] + " ");
}
}
// This code is contributed
// by inder_verma.
Output:
Sorted array
56 243 589 612 856 945 999
Improved By : inderDuMCA
Source
https://www.geeksforgeeks.org/merge-sort-with-o1-extra-space-merge-and-on-lg-n-time/
1309
Chapter 194
Input:
k = 3, n = 4
arr[][] = { {1, 3, 5, 7},
{2, 4, 6, 8},
{0, 9, 10, 11}} ;
Output: 0 1 2 3 4 5 6 7 8 9 10 11
A simple solution is to create an output array of size n*k and one by one copy all arrays
to it. Finally, sort the output array using any O(n Log n) sorting algorithm. This approach
takes O(nk Log nk) time.
One efficient solution is to first merge arrays into groups of 2. After first merging, we
have k/2 arrays. We again merge arrays in groups, now we have k/4 arrays. We keep doing it
unit we have one array left. The time complexity of this solution would O(nk Log k). How?
Every merging in first iteration would take 2n time (merging two arrays of size n). Since
there are total k/2 merging, total time in first iteration would be O(nk). Next iteration
would also take O(nk). There will be total O(Log k) iterations, hence time complexity is
O(nk Log k)
Another efficient solution is to use Min Heap. This Min Heap based solution has same
time complexity which is O(nk Log k). But for different sized arrays, this solution works
much better.
Following is detailed algorithm.
1. Create an output array of size n*k.
2. Create a min heap of size k and insert 1st element in all the arrays into the heap
1310
Chapter 194. Merge k sorted arrays Set 1
1311
Chapter 194. Merge k sorted arrays Set 1
1312
Chapter 194. Merge k sorted arrays Set 1
1313
Chapter 194. Merge k sorted arrays Set 1
Output:
Merged array is
1 2 6 9 12 20 23 34 34 90 1000 2000
Time Complexity: The main step is 3rd step, the loop runs n*k times. In every iteration
of loop, we call heapify which takes O(Logk) time. Therefore, the time complexity is O(nk
Logk).
Merge k sorted arrays Set 2 (Different Sized Arrays)
Thanks to vigneshfor suggesting this problem and initial solution. Please write comments if
you find anything incorrect, or you want to share more information about the topic discussed
above
Improved By : maxflex
Source
https://www.geeksforgeeks.org/merge-k-sorted-arrays/
1314
Chapter 195
Input : arr1[] = { 1, 3, 4, 5}
arr2[] = {2, 4, 6, 8}
Output : arr3[] = {1, 2, 3, 4, 5, 6, 7, 8}
Input : arr1[] = { 5, 8, 9}
arr2[] = {4, 7, 8}
Output : arr3[] = {4, 5, 7, 8, 8, 9}
We have discussed implementation of above method in Merge two sorted arrays with O(1)
extra space
Method 2 (O(n1 + n2) Time and O(n1 + n2) Extra Space)
The idea is to use Merge function of Merge sort.
1315
Chapter 195. Merge two sorted arrays
• Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to
next position in arr3[] and move ahead in arr3[] and the array whose element is
picked.
3. If there are are remaining elements in arr1[] or arr2[], copy them also in arr3[].
C++
1316
Chapter 195. Merge two sorted arrays
Java
1317
Chapter 195. Merge two sorted arrays
Python 3
1318
Chapter 195. Merge two sorted arrays
C#
// C# program to merge
// two sorted arrays
using System;
class GFG
{
// Merge arr1[0..n1-1] and
1319
Chapter 195. Merge two sorted arrays
1320
Chapter 195. Merge two sorted arrays
PHP
<?php
// PHP program to merge
// two sorted arrays
// Merge $arr1[0..$n1-1] and
// $arr2[0..$n2-1] into
// $arr3[0..$n1+$n2-1]
function mergeArrays(&$arr1, &$arr2,
$n1, $n2, &$arr3)
{
$i = 0;
$j = 0;
$k = 0;
// Traverse both array
while ($i < $n1 && $j < $n2)
{
// Check if current element
// of first array is smaller
// than current element of
// second array. If yes,
// store first array element
// and increment first array
// index. Otherwise do same
// with second array
if ($arr1[$i] < $arr2[$j])
$arr3[$k++] = $arr1[$i++];
else
$arr3[$k++] = $arr2[$j++];
}
// Store remaining elements
// of first array
while ($i < $n1)
$arr3[$k++] = $arr1[$i++];
// Store remaining elements
1321
Chapter 195. Merge two sorted arrays
Output:
Source
https://www.geeksforgeeks.org/merge-two-sorted-arrays/
1322
Chapter 196
This task is simple and O(m+n) if we are allowed to use extra space. But it becomes really
complicated when extra space is not allowed and doesn’t look possible in less than O(m*n)
worst case time.
The idea is to begin from last element of ar2[] and search it in ar1[]. If there is a greater
element in ar1[], then we move last element of ar1[] to ar2[]. To keep ar1[] and ar2[] sorted,
we need to place last element of ar2[] at correct place in ar1[]. We can use Insertion Sort
type of insertion for this. Below is algorithm:
1323
Chapter 196. Merge two sorted arrays with O(1) extra space
In above loop, elements in ar1[] and ar2[] are always kept sorted.
Below is C++ and Java implementation of above algorithm.
C++
// C++ program to merge two sorted arrays with O(1) extra space.
#include <bits/stdc++.h>
using namespace std;
// Merge ar1[] and ar2[] with O(1) extra space
void merge(int ar1[], int ar2[], int m, int n)
{
// Iterate through all elements of ar2[] starting from
// the last element
for (int i=n-1; i>=0; i--)
{
/* Find the smallest element greater than ar2[i]. Move all
elements one position ahead till the smallest greater
element is not found */
int j, last = ar1[m-1];
for (j=m-2; j >= 0 && ar1[j] > ar2[i]; j--)
ar1[j+1] = ar1[j];
// If there was a greater element
if (j != m-2 || last > ar2[i])
{
ar1[j+1] = ar2[i];
ar2[i] = last;
}
}
}
// Driver program
int main(void)
{
int ar1[] = {1, 5, 9, 10, 15, 20};
int ar2[] = {2, 3, 8, 13};
int m = sizeof(ar1)/sizeof(ar1[0]);
1324
Chapter 196. Merge two sorted arrays with O(1) extra space
int n = sizeof(ar2)/sizeof(ar2[0]);
merge(ar1, ar2, m, n);
cout << "After Merging nFirst Array: ";
for (int i=0; i<m; i++)
cout << ar1[i] << " ";
cout << "nSecond Array: ";
for (int i=0; i<n; i++)
cout << ar2[i] << " ";
return 0;
}
Java
1325
Chapter 196. Merge two sorted arrays with O(1) extra space
{
merge(arr1.length,arr2.length);
System.out.print("After Merging nFirst Array: ");
System.out.println(Arrays.toString(arr1));
System.out.print("Second Array: ");
System.out.println(Arrays.toString(arr2));
}
}
Python3
1326
Chapter 196. Merge two sorted arrays with O(1) extra space
merge(ar1, ar2, m, n)
print("After Merging \nFirst Array:", end="")
for i in range(m):
print(ar1[i] , " ", end="")
print("\nSecond Array: ", end="")
for i in range(n):
print(ar2[i] , " ", end="")
# This code is contributed
# by Anant Agarwal.
Output:
After Merging
First Array: 1 2 3 5 8 9
Second Array: 10 13 15 20
Time Complexity: The worst case time complexity of code/algorithm is O(m*n). The
worst case occurs when all elements of ar1[] are greater than all elements of ar2[].
Illustration:
1327
Chapter 196. Merge two sorted arrays with O(1) extra space
Source
https://www.geeksforgeeks.org/merge-two-sorted-arrays-o1-extra-space/
1328
Chapter 197
Examples:
Input : s1 : 9 4 2 1
s2: 8 17 3 10
Output : final stack: 1 2 3 4 8 9 10 17
Input : s1 : 5 7 2 6 4
s2 : 12 9 3
1329
Chapter 197. Merging and Sorting Two Unsorted Stacks
Create an empty stack to store result. We first insert elements of both stacks into the result.
Then we sort the result stack.
C++
1330
Chapter 197. Merging and Sorting Two Unsorted Stacks
res.push(s2.top());
s2.pop();
}
// Sort the result stack.
return sortStack(res);
}
// main function
int main()
{
stack<int> s1, s2;
s1.push(34);
s1.push(3);
s1.push(31);
s2.push(1);
s2.push(12);
s2.push(23);
// This is the temporary stack
stack<int> tmpStack = sortedMerge(s1, s2);
cout << "Sorted and merged stack :\n";
while (!tmpStack.empty()) {
cout << tmpStack.top() << " ";
tmpStack.pop();
}
}
Java
1331
Chapter 197. Merging and Sorting Two Unsorted Stacks
{
// pop out the first element
int tmp = input.peek();
input.pop();
// while temporary stack is not empty and
// top of stack is greater than temp
while (tmpStack.size() != 0 &&
tmpStack.peek() > tmp)
{
// pop from temporary stack and push
// it to the input stack
input.push(tmpStack.peek());
tmpStack.pop();
}
// push temp in tempory of stack
tmpStack.push(tmp);
}
}
static void sortedMerge(Stack<Integer> s1,
Stack<Integer> s2)
{
// Push contents of both stacks in result
while (s1.size() != 0) {
res.push(s1.peek());
s1.pop();
}
while (s2.size() != 0) {
res.push(s2.peek());
s2.pop();
}
// Sort the result stack.
sortStack(res);
}
// main function
public static void main(String args[])
{
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
s1.push(34);
s1.push(3);
s1.push(31);
1332
Chapter 197. Merging and Sorting Two Unsorted Stacks
s2.push(1);
s2.push(12);
s2.push(23);
sortedMerge(s1, s2);
System.out.println("Sorted and merged stack :");
while (tmpStack.size() != 0) {
System.out.print(tmpStack.peek() + " ");
tmpStack.pop();
}
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
C#
1333
Chapter 197. Merging and Sorting Two Unsorted Stacks
tmpStack.Pop();
}
// push temp in tempory of stack
tmpStack.Push(tmp);
}
return tmpStack;
}
static Stack<int> sortedMerge(ref Stack<int> s1,
ref Stack<int> s2)
{
// Push contents of both stacks in result
Stack<int> res = new Stack<int>();
while (s1.Count!=0) {
res.Push(s1.Peek());
s1.Pop();
}
while (s2.Count!=0) {
res.Push(s2.Peek());
s2.Pop();
}
// Sort the result stack.
return sortStack(ref res);
}
// main function
static void Main()
{
Stack<int> s1 = new Stack<int>();
Stack<int> s2 = new Stack<int>();
s1.Push(34);
s1.Push(3);
s1.Push(31);
s2.Push(1);
s2.Push(12);
s2.Push(23);
// This is the temporary stack
Stack<int> tmpStack = new Stack<int>();
tmpStack = sortedMerge(ref s1,ref s2);
Console.Write("Sorted and merged stack :\n");
while (tmpStack.Count!=0) {
Console.Write(tmpStack.Peek() + " ");
1334
Chapter 197. Merging and Sorting Two Unsorted Stacks
tmpStack.Pop();
}
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
Output:
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/merging-sorting-two-unsorted-stacks/
1335
Chapter 198
There are many cases to deal with: either ‘a’ or ‘b’ may be empty, during processing either
‘a’ or ‘b’ may run out first, and finally there’s the problem of starting the result list empty,
and building it up while going through ‘a’ and ‘b’.
Method 1 (first Concatenate then Sort)
In this case, we first append the two unsorted lists. Then we simply sort the concatenated
list.
C++
1336
Chapter 198. Merging two unsorted arrays in sorted order
// in sorted order
#include <bits/stdc++.h>
using namespace std;
// Function to merge array in sorted order
void sortedMerge(int a[], int b[], int res[],
int n, int m)
{
// Concatenate two arrays
int i = 0, j = 0, k = 0;
while (i < n) {
res[k] = a[i];
i += 1;
k += 1;
}
while (j < m) {
res[k] = b[j];
j += 1;
k += 1;
}
// sorting the res array
sort(res, res + n + m);
}
// Driver code
int main()
{
int a[] = { 10, 5, 15 };
int b[] = { 20, 3, 2, 12 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
// Final merge list
int res[n + m];
sortedMerge(a, b, res, n, m);
cout << "Sorted merged list :";
for (int i = 0; i < n + m; i++)
cout << " " << res[i];
cout << "n";
return 0;
}
Java
1337
Chapter 198. Merging two unsorted arrays in sorted order
1338
Chapter 198. Merging two unsorted arrays in sorted order
Python
C#
1339
Chapter 198. Merging two unsorted arrays in sorted order
int m)
{
// Concatenate two arrays
int i = 0, j = 0, k = 0;
while (i < n) {
res[k] = a[i];
i++;
k++;
}
while (j < m) {
res[k] = b[j];
j++;
k++;
}
// sorting the res array
Array.Sort(res);
}
/* Driver program to test above function */
public static void Main()
{
int []a = {10, 5, 15};
int []b = {20, 3, 2, 12};
int n = a.Length;
int m = b.Length;
// Final merge list
int []res=new int[n + m];
sortedMerge(a, b, res, n, m);
Console.Write("Sorted merged list :");
for (int i = 0; i < n + m; i++)
Console.Write(" " + res[i]);
}
}
// This code is contributed by nitin mittal.
Output :
1340
Chapter 198. Merging two unsorted arrays in sorted order
1341
Chapter 198. Merging two unsorted arrays in sorted order
int main()
{
int a[] = { 10, 5, 15 };
int b[] = { 20, 3, 2, 12 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
// Final merge list
int res[n + m];
sortedMerge(a, b, res, n, m);
cout << "Sorted merge list :";
for (int i = 0; i < n + m; i++)
cout << " " << res[i];
cout << "n";
return 0;
}
Java
1342
Chapter 198. Merging two unsorted arrays in sorted order
}
}
while (i < n) { // Merging remaining
// elements of a[] (if any)
res[k] = a[i];
i += 1;
k += 1;
}
while (j < m) { // Merging remaining
// elements of b[] (if any)
res[k] = b[j];
j += 1;
k += 1;
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int a[] = { 10, 5, 15 };
int b[] = { 20, 3, 2, 12 };
int n = a.length;
int m = b.length;
// Final merge list
int res[] = new int[n + m];
sortedMerge(a, b, res, n, m);
System.out.print( "Sorted merged list :");
for (int i = 0; i < n + m; i++)
System.out.print(" " + res[i]);
}
}
// This code is contributed by Arnav Kr. Mandal.
Python
1343
Chapter 198. Merging two unsorted arrays in sorted order
i, j, k = 0, 0, 0
while (i < n and j < m):
if (a[i] <= b[j]):
res[k] = a[i]
i += 1
k += 1
else:
res[k] = b[j]
j += 1
k += 1
while (i < n): # Merging remaining
# elements of a[] (if any)
res[k] = a[i]
i += 1
k += 1
while (j < m): # Merging remaining
# elements of b[] (if any)
res[k] = b[j]
j += 1
k += 1
# Driver code
a = [ 10, 5, 15 ]
b = [ 20, 3, 2, 12 ]
n = len(a)
m = len(b)
# Final merge list
res = [0 for i in range(n + m)]
sortedMerge(a, b, res, n, m)
print "Sorted merged list :"
for i in range(n + m):
print res[i],
# This code is contributed by Sachin Bisht
C#
1344
Chapter 198. Merging two unsorted arrays in sorted order
1345
Chapter 198. Merging two unsorted arrays in sorted order
above function */
public static void Main()
{
int []a = { 10, 5, 15 };
int []b = { 20, 3, 2, 12 };
int n = a.Length;
int m = b.Length;
// Final merge list
int []res = new int[n + m];
sortedMerge(a, b, res, n, m);
Console.Write( "Sorted merged list :");
for (int i = 0; i < n + m; i++)
Console.Write(" " + res[i]);
}
}
// This code is contributed by nitin mittal.
Output :
Source
https://www.geeksforgeeks.org/merging-two-unsorted-arrays-sorted-order/
1346
Chapter 199
Minimize the sum of product of two arrays with permutations allowed - GeeksforGeeks
Given two arrays, A and B, of equal size n, the task is to find the minimum value of A[0] *
B[0] + A[1] * B[1] +…+ A[n-1] * B[n-1]. Shuffling of elements of arrays A and B is allowed.
Examples :
The idea is to multiply minimum element of one array to maximum element of another array.
Algorithm to solve this problem:
1347
Chapter 199. Minimize the sum of product of two arrays with permutations allowed
Java
1348
Chapter 199. Minimize the sum of product of two arrays with permutations allowed
Arrays.sort(A);
Arrays.sort(B);
// Multiplying minimum value of A
// and maximum value of B
int result = 0;
for (int i = 0; i < n; i++)
result += (A[i] * B[n - i - 1]);
return result;
}
// Driven Program
public static void main(String[] args)
{
int A[] = { 3, 1, 1 };
int B[] = { 6, 5, 4 };
int n = A.length;
;
System.out.println(minValue(A, B, n));
}
}
// This code is contributed by vt_m
Python
1349
Chapter 199. Minimize the sum of product of two arrays with permutations allowed
B = [6, 5, 4]
n = len(A)
print minValue(A, B, n)
# Contributed by: Afzal Ansari
C#
1350
Chapter 199. Minimize the sum of product of two arrays with permutations allowed
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to calculate minimum
// sum of product of two arrays.
// Returns minimum sum of
// product of two arrays
// with permutations allowed
function minValue($A, $B, $n)
{
// Sort A and B so that minimum
// and maximum value can easily
// be fetched.
sort($A); sort($A , $n);
sort($B); sort($B , $n);
// Multiplying minimum value of
// A and maximum value of B
$result = 0;
for ($i = 0; $i < $n; $i++)
$result += ($A[$i] *
$B[$n - $i - 1]);
return $result;
}
// Driver Code
$A = array( 3, 1, 1 );
$B = array( 6, 5, 4 );
$n = sizeof($A) / sizeof($A[0]);
echo minValue($A, $B, $n) ;
// This code is contributed by nitin mittal.
?>
Output :
23
1351
Chapter 199. Minimize the sum of product of two arrays with permutations allowed
Source
https://www.geeksforgeeks.org/minimize-sum-product-two-arrays-permutations-allowed/
1352
Chapter 200
Minimum De-arrangements
present in array of AP
(Arithmetic Progression)
1353
Chapter 200. Minimum De-arrangements present in array of AP (Arithmetic Progression)
Java
1354
Chapter 200. Minimum De-arrangements present in array of AP (Arithmetic Progression)
import java.lang.*;
import java.util.Arrays;
public class GeeksforGeeks{
// function to count Dearrangement
public static int countDe(int arr[], int n){
int v[] = new int[n];
// create a copy of original array
for(int i = 0; i < n; i++)
v[i] = arr[i];
// sort the array
Arrays.sort(arr);
// traverse sorted array for
// counting mismatches
int count1 = 0;
for (int i = 0; i < n; i++)
if (arr[i] != v[i])
count1++;
// reverse the sorted array
Collections.reverse(Arrays.asList(arr));
// traverse reverse sorted array
// for counting mismatches
int count2 = 0;
for (int i = 0; i < n; i++)
if (arr[i] != v[i])
count2++;
// return minimum mismatch count
return (Math.min (count1, count2));
}
// driver code
public static void main(String argc[]){
int arr[] = {5, 9, 21, 17, 13};
int n = 5;
System.out.println("Minimum Dearrangement = "+
countDe(arr, n));
}
}
/*This code is contributed by Sagar Shukla.*/
1355
Chapter 200. Minimum De-arrangements present in array of AP (Arithmetic Progression)
Python3
1356
Chapter 200. Minimum De-arrangements present in array of AP (Arithmetic Progression)
# This code is contributed by "rishabh_jain".
C#
1357
Chapter 200. Minimum De-arrangements present in array of AP (Arithmetic Progression)
}
// Driver code
public static void Main()
{
int[] arr = new int[]{5, 9, 21, 17, 13};
int n = 5;
Console.WriteLine("Minimum Dearrangement = " +
countDe(arr, n));
}
}
// This code is contributed by mits
Output:
Minimum Dearrangement = 2
Source
https://www.geeksforgeeks.org/minimum-de-arrangements-present-array-ap-arithmetic-progression/
1358
Chapter 201
1359
Chapter 201. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
Algorithm:
calculateEnergy(mat, n)
Declare i_des, j_des, q
Initialize tot_energy = 0
for i = 0 to n-1
for j = 0 to n-1
q = mat[i][j] / n
i_des = q
j_des = mat[i][j] - (n * q)
tot_energy += abs(i_des - i) + abs(j_des - j)
return tot_energy
C++
1360
Chapter 201. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
q = mat[i][j] / n;
// final destination location (i_des, j_des) of
// the element mat[i][j] is being calculated
i_des = q;
j_des = mat[i][j] - (n * q);
// energy required for the moevement of the
// element mat[i][j] is calculated and then
// accumulated in the 'tot_energy'
tot_energy += abs(i_des - i) + abs(j_des - j);
}
}
// required total energy
return tot_energy;
}
// Driver program to test above
int main()
{
int mat[SIZE][SIZE] = { { 4, 7, 0, 3 },
{ 8, 5, 6, 1 },
{ 9, 11, 10, 2 },
{ 15, 13, 14, 12 } };
int n = 4;
cout << "Total energy required = "
<< calculateEnergy(mat, n) << " units";
return 0;
}
Java
1361
Chapter 201. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
1362
Chapter 201. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
}
}
// This code is contributed by Sagar Shukla
Python3
1363
Chapter 201. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
C#
// C# implementation to find
// the total energy required
// to rearrange the numbers
using System;
class GFG {
// function to find the total energy
// required to rearrange the numbers
public static int calculateEnergy(int[, ] mat,
int n)
{
int i_des, j_des, q;
int tot_energy = 0;
// nested loops to acess the elements
// of the given matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// store quotient
q = mat[i, j] / n;
// final destination location
// (i_des, j_des) of
// the element mat[i][j] is
// being calculated
i_des = q;
j_des = mat[i, j] - (n * q);
// energy required for the
// movement of the
// element mat[i][j] is
// calculated and then
// accumulated in the 'tot_energy'
tot_energy += Math.Abs(i_des - i) +
Math.Abs(j_des - j);
}
1364
Chapter 201. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
}
// required total energy
return tot_energy;
}
// Driver function
public static void Main()
{
int[, ] mat = new int[, ]{ { 4, 7, 0, 3 },
{ 8, 5, 6, 1 },
{ 9, 11, 10, 2 },
{ 15, 13, 14, 12 } };
int n = 4;
Console.Write("Total energy required = " +
calculateEnergy(mat, n) + " units");
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP implementation to find
// the total energy required
// to rearrange the numbers
// function to find the total energy
// required to rearrange the numbers
function calculateEnergy($mat, $n)
{
$i_des; $j_des; $q;
$tot_energy = 0;
// nested loops to acess the
// elements of the given matrix
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
// store quotient
$q = (int)($mat[$i][$j] / $n);
// final destination location
1365
Chapter 201. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
Output :
Source
https://www.geeksforgeeks.org/minimum-cost-sort-matrix-numbers-0-n2-1/
1366
Chapter 202
Simple Approach: A simple approach would be to try against all combinations of array
elements and check against each set of combination difference between the group with the
highest sum and the one with lowest sum. A total of n*(n-1)/2 such groups would be formed
(nC2).
1367
Chapter 202. Minimum difference between groups of size two
Time Complexity : O(n^3) To generate groups n^2 iterations will be needed and to check
against each group n iterations will be needed and hence n^3 iterations will be needed in
worst case.
Efficient Approach: Efficient approach would be to use the greedy approach. Sort the
whole array and generate groups by selecting one element from the start of the array and
one from the end.
Output:
1368
Chapter 202. Minimum difference between groups of size two
Source
https://www.geeksforgeeks.org/minimum-difference-between-groups-of-size-two/
1369
Chapter 203
Minimum difference between max and min of all K-size subsets - GeeksforGeeks
Given an array of integer values, we need to find the minimum difference between maximum
and minimum of all possible K-length subsets.
Examples :
1370
Chapter 203. Minimum difference between max and min of all K-size subsets
k = 2
Output : 1
We can solve this problem without iterating over all possible subsets by observing the fact
that our result subset will always be consecutive, once we sort the given array. The reason
is sorting brings value-wise close elements together.
We can prove above fact as follows – Suppose we chose number a1, a2, a3 … aK which are in
increasing order but not continuous, then our difference will be (aK – a1) but if we include
the number which was not taken earlier (let aR) then our K length subset will be a2, a3, …
aR, …. aK. In this case, our difference will (aK – a2) which must be smaller than (aK – a1)
because a2 > a1. So we can say that the subset which will contain our answer will always
be consecutive in sorted array.
Stating above fact, for solving the problem first we sort the array then we will iterate over
first (N – K) elements and each time we will take the difference between elements which are
K distant apart and our final answer will be minimum of them.
C++
1371
Chapter 203. Minimum difference between max and min of all K-size subsets
return res;
}
// Driver code
int main()
{
int arr[] = {10, 20, 30, 100, 101, 102};
int N = sizeof(arr) / sizeof(arr[0]);
int K = 3;
cout << minDifferenceAmongMaxMin(arr, N, K);
return 0;
}
Java
1372
Chapter 203. Minimum difference between max and min of all K-size subsets
return res;
}
// Driver code
public static void main(String[] args)
{
int arr[] = {10, 20, 30, 100, 101, 102};
int N = arr.length;
int K = 3;
System.out.print(
minDifferenceAmongMaxMin(arr, N, K));
}
}
// This code is contributed by Anant Agarwal.
Python3
1373
Chapter 203. Minimum difference between max and min of all K-size subsets
C#
1374
Chapter 203. Minimum difference between max and min of all K-size subsets
PHP
<?php
// PHP program to find minimum difference
// between max and min of all subset
// of K size
// returns min difference between max
// and min of any K-size subset
function minDifferenceAmongMaxMin($arr, $N,
$K)
{
$INT_MAX = 2;
// sort the array so that close
// elements come together.
sort($arr); sort($arr , $N);
// initialize result by a
// big integer number
$res = $INT_MAX;
// loop over first (N - K) elements
// of the array only
for ($i = 0; $i <= ($N - $K); $i++)
{
// get difference between max and
// min of current K-sized segment
$curSeqDiff = $arr[$i + $K - 1] -
$arr[$i];
$res = min($res, $curSeqDiff);
}
return $res;
}
1375
Chapter 203. Minimum difference between max and min of all K-size subsets
Output:
Source
https://www.geeksforgeeks.org/minimum-difference-max-min-k-size-subsets/
1376
Chapter 204
Input : arr[] = { 2, 2, 1, 3, 3, 3}
m = 3
Output : 1
Remove 1 and both 2's.So, only 3 will be
left that's why distinct id is 1.
Input : arr[] = { 2, 4, 1, 5, 3, 5, 1, 3}
m = 2
Output : 3
Remove 2 and 4 completely. So, remaining ids
are 1, 3 and 5 i.e. 3
1377
Chapter 204. Minimum number of distinct elements after removing m items
1378
Chapter 204. Minimum number of distinct elements after removing m items
cout << distinctIds(arr, n, m);
return 0;
}
Java
1379
Chapter 204. Minimum number of distinct elements after removing m items
Output:
Source
https://www.geeksforgeeks.org/minimum-number-of-distinct-elements-after-removing-m-items/
1380
Chapter 205
Input : 3 10
10 20 30
Output : 1
In the first sample we can add number 9
to array (10, 20, 30). The resulting array
(9, 10, 20, 30) will have a median in
position (4+1)/2 = 2, that is, 10
Input : 3 4
1 2 3
Output : 4
In the second sample you should add numbers
4, 5, 5, 5. The resulting array has median
equal to 4.
First Approach:- The approach is to add one more number x to the array until the median
of the array equals to x. Below is the implementation of the above approach:-
C++
1381
Chapter 205. Minimum number of elements to add to make median equals x
PHP
<?php
// PHP program to find minimum
// number of elements needs to
// add to the array so that its
// median equals x.
// Returns count of elements
// to be added to make median
// x. This function assumes
// that a[] has enough extra space.
function minNumber($a, $n, $x)
{
// to sort the array in
// increasing order.
1382
Chapter 205. Minimum number of elements to add to make median equals x
sort($a);
$k;
for ($k = 0;
$a[($n - 1) / 2] != $x; $k++)
{
$a[$n++] = $x;
sort($a);
}
return $k;
}
// Driver code
$x = 10;
$a = array (10, 20, 30);
$n = 3;
echo minNumber($a, $n, $x),"\n";
// This code is contributed by ajit
?>
Output :
1383
Chapter 205. Minimum number of elements to add to make median equals x
Java
1384
Chapter 205. Minimum number of elements to add to make median equals x
int n, int x)
{
int l = 0, h = 0, e = 0;
for (int i = 0; i < n; i++)
{
// no. of elements equals to
// x, that is, e.
if (a[i] == x)
e++;
// no. of elements greater
// than x, that is, h.
else if (a[i] > x)
h++;
// no. of elements smaller
// than x, that is, l.
else if (a[i] < x)
l++;
}
int ans = 0;
if (l > h)
ans = l - h;
else if (l < h)
ans = h - l - 1;
// subtract the no. of elements
// that are equal to x.
return ans + 1 - e;
}
// Driven Program
public static void main(String[] args)
{
int x = 10;
int a[] = { 10, 20, 30 };
int n = a.length;
System.out.println(
minNumber(a, n, x));
}
}
// This code is contributed by
// Prasad Kshirsagar
Python3
1385
Chapter 205. Minimum number of elements to add to make median equals x
C#
1386
Chapter 205. Minimum number of elements to add to make median equals x
1387
Chapter 205. Minimum number of elements to add to make median equals x
int n = a.Length;
Console.WriteLine(
minNumber(a, n, x));
}
}
// This code is contributed
// by anuj_67.
PHP
<?php
// PHP program to find minimum
// number of elements to add so
// that its median equals x.
function minNumber($a, $n, $x)
{
$l = 0; $h = 0; $e = 0;
for ($i = 0; $i < $n; $i++)
{
// no. of elements equals
// to x, that is, e.
if ($a[$i] == $x)
$e++;
// no. of elements greater
// than x, that is, h.
else if ($a[$i] > $x)
$h++;
// no. of elements smaller
// than x, that is, l.
else if ($a[$i] < $x)
$l++;
}
$ans = 0;
if ($l > $h)
$ans = $l - $h;
else if ($l < $h)
$ans = $h - $l - 1;
// subtract the no. of elements
// that are equal to x.
return $ans + 1 - $e;
}
1388
Chapter 205. Minimum number of elements to add to make median equals x
// Driver code
$x = 10;
$a = array (10, 20, 30);
$n = sizeof($a) ;
echo minNumber($a, $n, $x), "\n";
// This code is contributed by jit_t
?>
Output :
Source
https://www.geeksforgeeks.org/minimum-number-elements-add-make-median-equals-x/
1389
Chapter 206
We basically need to find the most frequent element in the array. The result is equal to the
frequency of the most frequent element.
A simple solution is to run two nested loops to count frequency of every element and
return the frequency of the most frequent element. Time complexity of this solution is
O(n2 ).
A better solution is to first sort the array and then start count number of repetitions of
elements in an iterative manner as all repetition of any number lie beside the number itself.
By this method you can find the maximum frequency or repetition by simply traversing the
sorted array. This approach will cost O(nlogn) time complexity
C++
1390
Chapter 206. Minimum number of subsets with distinct elements
Java
1391
Chapter 206. Minimum number of subsets with distinct elements
1392
Chapter 206. Minimum number of subsets with distinct elements
/* This code is contributed by Sagar Shukla */
Python3
C#
1393
Chapter 206. Minimum number of subsets with distinct elements
1394
Chapter 206. Minimum number of subsets with distinct elements
}
/* This code is contributed by Vt_m */
Output :
Output :
1395
Chapter 206. Minimum number of subsets with distinct elements
Source
https://www.geeksforgeeks.org/minimum-number-subsets-distinct-elements/
1396
Chapter 207
for each i: .
Approach :
1397
Chapter 207. Minimum number of subtract operation to make an array decreasing
If ( (arr[i] - arr[i-1]) % k == 0 )
then noOfSubtraction++
Modify arr[i];
arr[i] =
1398
Chapter 207. Minimum number of subtract operation to make an array decreasing
// Driver Code
int main()
{
int arr[] = { 1, 1, 2, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
int k = 5;
cout << min_noOf_operation(arr, N, k) << endl;
return 0;
}
Java
1399
Chapter 207. Minimum number of subtract operation to make an array decreasing
return res;
}
// driver function
public static void main(String argc[]){
int arr = { 1, 1, 2, 3 };
int N = 4;
int k = 5;
System.out.println(min_noOf_operation(arr,
N, k));
}
}
/* This code is contributed by Sagar Shukla */
Python3
1400
Chapter 207. Minimum number of subtract operation to make an array decreasing
# Driver Code
arr = [ 1, 1, 2, 3 ]
N = len(arr)
k = 5
print(min_noOf_operation(arr, N, k))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to make an
// array decreasing
using System;
public class GfG{
// Function to count minimum no of operation
public static int min_noOf_operation(int []arr,
int n, int k)
{
int noOfSubtraction;
int res = 0;
for (int i = 1; i < n; i++) {
noOfSubtraction = 0;
if (arr[i] > arr[i - 1]) {
// Count how many times
// we have to subtract.
noOfSubtraction = (arr[i] - arr[i - 1]) / k;
// Check an additional subtraction
// is required or not.
if ((arr[i] - arr[i - 1]) % k != 0)
noOfSubtraction++;
// Modify the value of arr[i]
arr[i] = arr[i] - k * noOfSubtraction;
}
// Count total no of subtraction
res = res + noOfSubtraction;
}
return res;
}
1401
Chapter 207. Minimum number of subtract operation to make an array decreasing
// driver function
public static void Main()
{
int []arr = { 1, 1, 2, 3 };
int N = 4;
int k = 5;
Console.WriteLine(min_noOf_operation(arr,
N, k));
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to make an array decreasing
// Function to count minimum no of operation
function min_noOf_operation($arr, $n, $k)
{
$noOfSubtraction;
$res = 0;
for($i = 1; $i < $n; $i++)
{
$noOfSubtraction = 0;
if ($arr[$i] > $arr[$i - 1])
{
// Count how many times we
// have to subtract.
$noOfSubtraction = ($arr[$i] -
$arr[$i - 1]) / $k;
// Check an additional subtraction
// is required or not.
if (($arr[$i] - $arr[$i - 1])
% $k != 0)
$noOfSubtraction++;
// Modify the value of arr[i].
$arr[$i] = $arr[$i] - $k *
$noOfSubtraction;
}
1402
Chapter 207. Minimum number of subtract operation to make an array decreasing
// Count total no of
// operation/subtraction .
$res = $res + $noOfSubtraction;
}
return floor($res);
}
// Driver Code
$arr = array(1, 1, 2, 3);
$N = count($arr);
$k = 5;
echo min_noOf_operation($arr, $N, $k) ;
// This code is contributed by anuj_67.
?>
Output :
Source
https://www.geeksforgeeks.org/find-minimum-number-operation-make-array-decreasing/
1403
Chapter 208
Input : {4, 3, 2, 1}
Output : 2
Explanation : Swap index 0 with 3 and 1 with 2 to
form the sorted array {1, 2, 3, 4}.
Input : {1, 5, 4, 3, 2}
Output : 2
This can be easily done by visualizing the problem as a graph. We will have n nodes and
an edge directed from node i to node j if the element at i’th index must be present at j’th
index in the sorted array.
The graph will now contain many non-intersecting cycles. Now a cycle with 2 nodes will
only require 1 swap to reach the correct ordering, similarly a cycle with 3 nodes will only
require 2 swap to do so.
1404
Chapter 208. Minimum number of swaps required to sort an array
Hence,
k
ans = Σi = 1 (cycle_size – 1)
where k is the number of cycles
Below is the C++ implementation of the idea.
C++
1405
Chapter 208. Minimum number of swaps required to sort an array
Java
1406
Chapter 208. Minimum number of swaps required to sort an array
// Create two arrays and use as pairs where first
// array is element and second array
// is position of first element
ArrayList <Pair <Integer, Integer> > arrpos =
new ArrayList <Pair <Integer, Integer> > ();
for (int i = 0; i < n; i++)
arrpos.add(new Pair <Integer, Integer> (arr[i], i));
// Sort the array by array element values to
// get right position of every element as the
// elements of second array.
arrpos.sort(new Comparator<Pair<Integer, Integer>>()
{
@Override
public int compare(Pair<Integer, Integer> o1,
Pair<Integer, Integer> o2)
{
if (o1.getKey() > o2.getKey())
return -1;
// We can change this to make it then look at the
// words alphabetical order
else if (o1.getKey().equals(o2.getKey()))
return 0;
else
return 1;
}
});
// To keep track of visited elements. Initialize
// all elements as not visited or false.
Boolean[] vis = new Boolean[n];
Arrays.fill(vis, false);
// Initialize result
int ans = 0;
// Traverse array elements
for (int i = 0; i < n; i++)
{
// already swapped and corrected or
// already present at correct pos
if (vis[i] || arrpos.get(i).getValue() == i)
continue;
// find out the number of node in
1407
Chapter 208. Minimum number of swaps required to sort an array
[/sourcecode]
Python3
1408
Chapter 208. Minimum number of swaps required to sort an array
1409
Chapter 208. Minimum number of swaps required to sort an array
# Driver Code
arr = [1, 5, 4, 3, 2]
print(minSwaps(arr))
# This code is contributed
# by Dharan Aditya
Output:
Source
https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/
1410
Chapter 209
Minimum partitions of
maximum size 2 and sum
limited by given value
Minimum partitions of maximum size 2 and sum limited by given value - GeeksforGeeks
Given an array arr[] of positive numbers, find minimum number of sets in array which satisfy
following property,
1. A set can contain maximum two elements in it. The two elements need not to be
contiguous.
2. Sum of elements of set should be less then or equal to given Key. It may be assumed
that given key is greater than or equal to the largest array element.
Examples:
The idea is to first sort the array, then followtwo pointer approach. We begin two pointers
from two corners of the sorted array. If their sum is smaller than or equal to given key, then
we make set of them, else we consider the last element alone.
Below is the implementation of the above approach :
C++
1411
Chapter 209. Minimum partitions of maximum size 2 and sum limited by given value
Java
1412
Chapter 209. Minimum partitions of maximum size 2 and sum limited by given value
int i, j;
// sort the array
Arrays.sort(arr);
// if sum of ith smaller and jth larger element is
// less than key, then pack both numbers in a set
// otherwise pack the jth larger number
// alone in the set
for (i = 0, j = n - 1; i <= j; ++i)
if (arr[i] + arr[j] <= key)
j--;
// After ending of loop i will contain minimum
// number of sets
return i;
}
public static void main (String[] args) {
int []arr = { 3, 5, 3, 4 };
int n =arr.length;
int key = 5;
System.out.println( minimumSets(arr, n, key));
}
}
// This code is contributed by chandan_jnu.
C#
1413
Chapter 209. Minimum partitions of maximum size 2 and sum limited by given value
PHP
<?php
// PHP program to count minimum
// number of partitions of size
// 2 and sum smaller than or
// equal to given key.
function minimumSets($arr, $n, $key)
{
$i; $j;
// sort the array
sort($arr);
// if sum of ith smaller and
// jth larger element is less
// than key, then pack both
// numbers in a set otherwise
// pack the jth larger number
// alone in the set
1414
Chapter 209. Minimum partitions of maximum size 2 and sum limited by given value
Output:
Source
https://www.geeksforgeeks.org/minimum-partitions-of-maximum-size-2-and-sum-limited-by-given-value/
1415
Chapter 210
Input : 11 8 5 7 5 100
k = 4
Output : 1400
The idea is simple, we find the smallest k elements and print multiplication of them. In
below implementation, we have used simple Heap based approach where we insert array
elements into a min heap and then find product of top k elements.
C++
1416
Chapter 210. Minimum product of k integers in an array of positive Integers
{
priority_queue<int, vector<int>, greater<int> > pq;
for (int i = 0; i < n; i++)
pq.push(arr[i]);
int count = 0, ans = 1;
// One by one extract items from max heap
while (pq.empty() == false && count < k) {
ans = ans * pq.top();
pq.pop();
count++;
}
return ans;
}
// Driver code
int main()
{
int arr[] = {198, 76, 544, 123, 154, 675};
int k = 2;
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Minimum product is "
<< minProduct(arr, n, k);
return 0;
}
Python3
1417
Chapter 210. Minimum product of k integers in an array of positive Integers
return ans;
# Driver method
arr = [198, 76, 544, 123, 154, 675]
k = 2
n = len(arr)
print ("Minimum product is",
minProduct(arr, n, k))
Output:
Source
https://www.geeksforgeeks.org/minimum-product-k-integers-array-positive-integers/
1418
Chapter 211
Input : 11 8 5 7 5 100
Output : 25
Explanation : The minimum product of any
two numbers will be 5 * 5 = 25.
Simple Approach : A simple approach will be to run two nested loops to generate all
possible pair of elements and keep track of the minimum product.
Time Complexity: O( n * n)
Auxiliary Space: O( 1 )
Better Approach: An efficient approach will be to first sort the given array and print the
product of first two numbers, sorting will take O(n log n). Answer will be then a[0] * a[1]
Time Complexity: O( n * log(n))
Auxiliary Space: O( 1 )
Best Approach: The idea is linearly traverse given array and keep track of minimum two
elements. Finally return product of two minimum elements.
1419
Chapter 211. Minimum product pair an array of positive Integers
Java
1420
Chapter 211. Minimum product pair an array of positive Integers
1421
Chapter 211. Minimum product pair an array of positive Integers
Python3
# Python program to
# calculate minimum
# product of a pair
# Function to calculate
# minimum product
# of pair
def printMinimumProduct(arr,n):
# Initialize first and second
# minimums. It is assumed that the
# array has at least two elements.
first_min = min(arr[0], arr[1])
second_min = max(arr[0], arr[1])
# Traverse remaining array and keep
# track of two minimum elements (Note
# that the two minimum elements may
# be same if minimum element appears
# more than once)
# more than once)
for i in range(2,n):
if (arr[i] < first_min):
second_min = first_min
first_min = arr[i]
elif (arr[i] < second_min):
second_min = arr[i]
return first_min * second_min
# Driver code
a= [ 11, 8 , 5 , 7 , 5 , 100 ]
n = len(a)
print(printMinimumProduct(a,n))
# This code is contributed
# by Anant Agarwal.
C#
1422
Chapter 211. Minimum product pair an array of positive Integers
// product of a pair
using System;
class GFG {
// Function to calculate minimum
// product of pair
static int printMinimumProduct(int []arr,
int n)
{
// Initialize first and second
// minimums. It is assumed that
// the array has at least two
// elements.
int first_min = Math.Min(arr[0],
arr[1]);
int second_min = Math.Max(arr[0],
arr[1]);
// Traverse remaining array and
// keep track of two minimum
// elements (Note that the two
// minimum elements may be same
// if minimum element appears
// more than once)
for (int i = 2; i < n; i++)
{
if (arr[i] < first_min)
{
second_min = first_min;
first_min = arr[i];
}
else if (arr[i] < second_min)
second_min = arr[i];
}
return first_min * second_min;
}
/* Driver program to test above
function */
public static void Main()
{
int []a = { 11, 8 , 5 , 7 ,
5 , 100 };
int n = a.Length;
1423
Chapter 211. Minimum product pair an array of positive Integers
Console.WriteLine(
printMinimumProduct(a, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to calculate minimum
// product of a pair
// Function to calculate minimum
// product of pair
function printMinimumProduct($arr, $n)
{
// Initialize first and second
// minimums. It is assumed that the
// array has at least two elements.
$first_min = min($arr[0], $arr[1]);
$second_min = max($arr[0], $arr[1]);
// Traverse remaining array and keep
// track of two minimum elements (Note
// that the two minimum elements may
// be same if minimum element appears
// more than once)
// more than once)
for ($i = 2; $i < $n; $i++)
{
if ($arr[$i] < $first_min)
{
$second_min = $first_min;
$first_min = $arr[$i];
}
else if ($arr[$i] < $second_min)
$second_min = $arr[$i];
}
return $first_min * $second_min;
}
// Driver Code
$a = array(11, 8 , 5 , 7 , 5 , 100);
$n = sizeof($a);
1424
Chapter 211. Minimum product pair an array of positive Integers
echo(printMinimumProduct($a, $n));
// This code is contributed by Ajit.
?>
Output:
25
Source
https://www.geeksforgeeks.org/minimum-product-pair-an-array-of-positive-integers/
1425
Chapter 212
Input : a[] = { 0, 0, 0 }
Output : 0
A simple solution is to generate all subsets, find product of every subset and return maximum
product.
A better solution is to use the below facts.
1. If there are even number of negative numbers and no zeros, the result is the product
of all except the largest valued negative number.
2. If there are an odd number of negative numbers and no zeros, the result is simply the
product of all.
1426
Chapter 212. Minimum product subset of an array
3. If there are zeros and positive, no negative, the result is 0. The exceptional case
is when there is no negative number and all other elements positive then our result
should be the first minimum positive number.
C++
1427
Chapter 212. Minimum product subset of an array
Java
1428
Chapter 212. Minimum product subset of an array
1429
Chapter 212. Minimum product subset of an array
Python3
1430
Chapter 212. Minimum product subset of an array
C#
1431
Chapter 212. Minimum product subset of an array
1432
Chapter 212. Minimum product subset of an array
PHP
<?php
// PHP program to find maximum
// product of a subset.
// Function to find maximum
// product of a subset
function minProductSubset($a, $n)
{
if ($n == 1)
1433
Chapter 212. Minimum product subset of an array
return $a[0];
// Find count of negative numbers,
// count of zeros, maximum valued
// negative number, minimum valued
// positive number and product
// of non-zero numbers
$max_neg = PHP_INT_MIN;
$min_pos = PHP_INT_MAX;
$count_neg = 0; $count_zero = 0;
$prod = 1;
for ($i = 0; $i < $n; $i++)
{
// If number is 0, we don't
// multiply it with product.
if ($a[$i] == 0)
{
$count_zero++;
continue;
}
// Count negatives and keep
// track of maximum valued
// negative.
if ($a[$i] < 0)
{
$count_neg++;
$max_neg = max($max_neg, $a[$i]);
}
// Track minimum positive
// number of array
if ($a[$i] > 0)
$min_pos = min($min_pos, $a[$i]);
$prod = $prod * $a[$i];
}
// If there are all zeros
// or no negative number
// present
if ($count_zero == $n ||
($count_neg == 0 &&
$count_zero > 0))
return 0;
// If there are all positive
1434
Chapter 212. Minimum product subset of an array
if ($count_neg == 0)
return $min_pos;
// If there are even number of
// negative numbers and count_neg
// not 0
if (!($count_neg & 1) &&
$count_neg != 0)
{
// Otherwise result is product of
// all non-zeros divided by maximum
// valued negative.
$prod = $prod / $max_neg;
}
return $prod;
}
// Driver code
$a = array( -1, -1, -2, 4, 3 );
$n = sizeof($a);
echo(minProductSubset($a, $n));
// This code is contributed by Ajit.
?>
Output:
-24
Source
https://www.geeksforgeeks.org/minimum-product-subset-array/
1435
Chapter 213
Input : n = 4
a[] = {4, 1, 8, 7}
b[] = {2, 3, 6, 5}
Output : 6
The solution to the problem is a simple greedy approach. It consists of two steps.
Step 1 : Sort both the arrays in O (n log n) time.
Step 2 : Find absolute difference of each pair of corresponding elements (elements at
same index) of both arrays and add the result to the sum S. The time complexity of this
step is O(n).
Hence, the overall time complexity of the program is O(n log n).
C++
1436
Chapter 213. Minimum sum of absolute difference of pairs of two arrays
Java
1437
Chapter 213. Minimum sum of absolute difference of pairs of two arrays
Python3
1438
Chapter 213. Minimum sum of absolute difference of pairs of two arrays
C#
PHP
<?php
// PHP program to find minimum sum
// of absolute differences of two
// arrays.
1439
Chapter 213. Minimum sum of absolute difference of pairs of two arrays
// Returns minimum possible pairwise
// absolute difference of two arrays.
function findMinSum($a, $b, $n)
{
// Sort both arrays
sort($a);
sort($a, $n);
sort($b);
sort($b, $n);
// Find sum of absolute
// differences
$sum= 0 ;
for ($i = 0; $i < $n; $i++)
$sum = $sum + abs($a[$i] -
$b[$i]);
return $sum;
}
// Driver Code
// Both a[] and b[] must
// be of same size.
$a = array(4, 1, 8, 7);
$b = array(2, 3, 6, 5);
$n = sizeof($a);
echo(findMinSum($a, $b, $n));
// This code is contributed by nitin mittal.
?>
Output :
Source
https://www.geeksforgeeks.org/minimum-sum-absolute-difference-pairs-two-arrays/
1440
Chapter 214
Input: [6, 8, 4, 5, 2, 3]
Output: 604
The minimum sum is formed by numbers
358 and 246
Input: [5, 3, 0, 7, 4]
Output: 82
The minimum sum is formed by numbers
35 and 047
A minimum number will be formed from set of digits when smallest digit appears at most
significant position and next smallest digit appears at next most significant position ans so
on..
The idea is to sort the array in increasing order and build two numbers by alternating
picking digits from the array. So first number is formed by digits present in odd positions in
the array and second number is formed by digits from even positions in the array. Finally,
we return the sum of first and second number.
Below is the implementation of above idea.
C/C++
1441
Chapter 214. Minimum sum of two numbers formed from digits of an array
Java
1442
Chapter 214. Minimum sum of two numbers formed from digits of an array
{
// sort the array
Arrays.sort(arr);
// let two numbers be a and b
int a = 0, b = 0;
for (int i = 0; i < n; i++)
{
// fill a and b with every alternate
// digit of input array
if (i % 2 != 0)
a = a * 10 + arr[i];
else
b = b * 10 + arr[i];
}
// return the sum
return a + b;
}
//driver code
public static void main (String[] args)
{
int arr[] = {6, 8, 4, 5, 2, 3};
int n = arr.length;
System.out.print("Sum is "
+ solve(arr, n));
}
}
//This code is contributed by Anant Agarwal.
Python3
# Python3 program to find minimum sum of two
# numbers formed from digits of the array.
# Function to find and return minimum sum of
# two numbers formed from digits of the array.
def solve(arr, n):
# sort the array
arr.sort()
1443
Chapter 214. Minimum sum of two numbers formed from digits of an array
C#
1444
Chapter 214. Minimum sum of two numbers formed from digits of an array
}
// return the sum
return a + b;
}
// Driver code
public static void Main ()
{
int []arr = {6, 8, 4, 5, 2, 3};
int n = arr.Length;
Console.WriteLine("Sum is " + solve(arr, n));
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program to find minimum
// sum of two numbers formed
// from digits of the array.
// Function to find and return
// minimum sum of two numbers
// formed from digits of the array.
function solve($arr, $n)
{
// sort the array
sort($arr); sort($arr , $n);
// let two numbers be a and b
$a = 0; $b = 0;
for ($i = 0; $i < $n; $i++)
{
// fill a and b with every
// alternate digit of input array
if ($i & 1)
$a = $a * 10 + $arr[$i];
else
$b = $b * 10 + $arr[$i];
}
// return the sum
return $a + $b;
}
1445
Chapter 214. Minimum sum of two numbers formed from digits of an array
// Driver code
$arr = array(6, 8, 4, 5, 2, 3);
$n = sizeof($arr);
echo "Sum is " , solve($arr, $n);
// This code is contributed by nitin mittal.
?>
Output :
Sum is 604
Source
https://www.geeksforgeeks.org/minimum-sum-two-numbers-formed-digits-array/
1446
Chapter 215
Minimum swap required to convert binary tree to binary search tree - GeeksforGeeks
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index
2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum
number of swap required to convert it into Binary Search Tree.
Examples:
Input : arr[] = { 1, 2, 3 }
Output : 1
Binary tree of the given array:
1447
Chapter 215. Minimum swap required to convert binary tree to binary search tree
The idea is to use the fact that inorder traversal of Binary Search Tree is in increasing order
of their value.
So, find the inorder traversal of the Binary Tree and store it in the array and try to sort the
array. The minimum number of swap required to get the array sorted will be the answer.
Please refer below post to find minimum number of swaps required to get the array sorted.
Minimum number of swaps required to sort an array
Time Complexity: O(n log n).
Exercise: Can we extend this to normal binary tree, i.e., a binary tree represented using
left and right pointers, and not necessarily complete?
Source
https://www.geeksforgeeks.org/minimum-swap-required-convert-binary-tree-binary-search-tree/
1448
Chapter 216
Input : [0, 0, 1, 0, 1, 0, 1, 1]
Output : 3
1st swap : [0, 0, 1, 0, 0, 1, 1, 1]
2nd swap : [0, 0, 0, 1, 0, 1, 1, 1]
3rd swap : [0, 0, 0, 0, 1, 1, 1, 1]
Approach :
This can be done by finding number of zeroes to the right side of every 1 and add them. In
order to sort the array every one always has to perform a swap operation with every zero
on its right side. So the total number of swap operations for a particular 1 in array is the
number of zeroes on its right hand side. Find the number of zeroes on right side for every
one i.e. the number of swaps and add them all to obtain the total number of swaps.
Implementation :
C++
1449
Chapter 216. Minimum swaps required to Sort Binary array
Java
1450
Chapter 216. Minimum swaps required to Sort Binary array
Python3
1451
Chapter 216. Minimum swaps required to Sort Binary array
noOfZeroes[n - 1] = 1 - arr[n - 1]
for i in range(n-2, -1, -1) :
noOfZeroes[i] = noOfZeroes[i + 1]
if (arr[i] == 0) :
noOfZeroes[i] = noOfZeroes[i] + 1
# Count total number of swaps by adding
# number of zeroes on right side of
# every one.
for i in range(0, n) :
if (arr[i] == 1) :
count = count + noOfZeroes[i]
return count
# Driver code
arr = [ 0, 0, 1, 0, 1, 0, 1, 1 ]
n = len(arr)
print (findMinSwaps(arr, n))
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
1452
Chapter 216. Minimum swaps required to Sort Binary array
Output :
Source
https://www.geeksforgeeks.org/minimum-swaps-required-sort-binary-array/
1453
Chapter 217
Approach: Before discussing the approach, we have to assume that here we are not sup-
posed to swap the pairs. We just need to count the minimum number of swaps so that if
we provide the newly created array to the binary search, we can get the position of k. In
order to do so, we need to pass the given array to binary search and focus on the following
things:-
1454
Chapter 217. Minimum swaps so that binary search can be applied
• Before going to the binary search we need to calculate the number of minimum ele-
ments i.e. num_min of k and number of maximum elements i.e. num_max of k.
Here, num_min denotes the number of smaller available elements of k and num_max
denotes the number of greater available elements that we can use for swapping
• The actual position of k in the given array.
Now following are the test cases that will occur during implementing the binary search:-
Case 1: If arr[mid] is greater than k, but position of k is greater than mid. Binary search
would take us to (arr[0] to arr[mid-1]). But actually our element is in between (arr[mid+1] to
arr[last element]). So, in order to go in the right direction, we need something smaller than k
so that we can swap it with arr[mid] and we can go between arr[mid+1] to arr[last_element].
So, here we require one swap i.e. need_minimum.
Case 2: If arr[mid] is less than k but position of k is smaller than mid. Binary search would
take us to (arr[mid+1] to arr[last_element]). But actually our element is in between (arr[0]
to arr[mid-1]). So, in order to go in the right direction, we need something greater than k
so that we can swap it with arr[mid] and we can go between arr[0] to arr[mid-1]. So, here
we required one swap i.e. need_maximum.
Case 3:
If arr[mid] is greater than k and position of k is lesser than mid. Now, in this case binary
search would work fine. But wait, here is the important thing on which we have to work on.
As we know in this case binary search will work fine, arr[mid] is at right position so this will
not be used in any swap so here we have to decrease the one of it’s greater available element
i.e. from num_max. Same goes with the case when arr[mid] is lesser than k and position
of k is greater than mid. Here, we have to decrease one of it’s smaller available element i.e.
from num_min.
Case 4: If arr[mid] == k Or pos == mid then we can easily come out from the binary
search.
So, till now we have calculated the need_minimum i.e. number of minimum elements
required for swapping, need_maximum i.e. number of maximum elements required for
swapping, num_max i.e. total number of greater elements from k that are still available for
swapping and num_min i.e. total number of minimum elements from k that are available
for swapping.
Now here we have to consider two cases:
Case 1: If need_minimum is greater than need_maximum. In this case, we have to
swap all these needed maximum elements with the smaller of k. So we have to use the
smaller elements from num_min. Now all the need_maximum swaps are done. Here the
main thing is that when we swapped all these needed maximum elements with smaller
elements, these smaller elements got their right positions. So, indirectly we have done some
of the needed smaller elements swaps and that will be calculated as need_minimum –
need_maximum and also available num_min will be num_min – need_maximum.
Now, we have to calculate the remaining need_minimum swaps. We can calculate these
swaps, if we have enough num_min i.e. num_min > need_minimum. For this case, swaps
will be need_maximum + need_minimum otherwise it will be -1. The same concept
goes with the case when we have need_minimum is smaller than need_maximum.
1455
Chapter 217. Minimum swaps so that binary search can be applied
1456
Chapter 217. Minimum swaps so that binary search can be applied
break;
}
else if (arr[mid] > k) {
// If we need minimum
// element swap.
if (pos > mid)
need_minimum++;
else
// Else the elemnt is
// at the right position.
num_min--;
left = mid + 1;
}
else {
if (pos < mid)
// If we need maximum
// element swap.
need_maximum++;
else
// Else element is at
// the right position
num_max--;
right = mid - 1;
}
}
// Calculating the required swaps.
if (need_minimum > need_maximum) {
swaps = swaps + need_maximum;
num_min = num_min - need_maximum;
need_minimum = need_minimum - need_maximum;
need_maximum = 0;
}
else {
swaps = swaps + need_minimum;
num_max = num_max - need_minimum;
need_maximum = need_maximum - need_minimum;
1457
Chapter 217. Minimum swaps so that binary search can be applied
need_minimum = 0;
}
// If it is impossible.
if (need_maximum > num_max || need_minimum > num_min)
return -1;
else
return (swaps + need_maximum + need_minimum);
}
// Driver function
int main()
{
int arr[] = { 3, 10, 6, 7, 2, 5, 4 }, k = 4;
int n = sizeof(arr) / sizeof(arr[0]);
cout << findMinimumSwaps(arr, n, k);
}
Output:
Source
https://www.geeksforgeeks.org/minimum-swaps-so-that-binary-search-can-be-applied/
1458
Chapter 218
This problem can be solved by modifying the array B. We save the index of array A elements
in array B i.e. if ith element of array A is at jth position in array B, then we will make
arrB[i] = j
For above given example, modified array B will be, arrB = {3, 1, 0, 2}. This modified
array represents distribution of array A element in array B and our goal is to sort this
modified array in minimum number of swaps because after sorting only array B element will
be aligned with array A elements.
Now count of minimum swaps for sorting an array can be found by visualizing the problem
as a graph, this problem is already explained inprevious article.
So we count these swaps in modified array and that will be our final answer.
Please see below code for better understanding.
1459
Chapter 218. Minimum swaps to make two arrays identical
#include <bits/stdc++.h>
using namespace std;
// Function returns the minimum number of swaps
// required to sort the array
// This method is taken from below post
// https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/
int minSwapsToSort(int arr[], int n)
{
// Create an array of pairs where first
// element is array element and second element
// is position of first element
pair<int, int> arrPos[n];
for (int i = 0; i < n; i++)
{
arrPos[i].first = arr[i];
arrPos[i].second = i;
}
// Sort the array by array element values to
// get right position of every element as second
// element of pair.
sort(arrPos, arrPos + n);
// To keep track of visited elements. Initialize
// all elements as not visited or false.
vector<bool> vis(n, false);
// Initialize result
int ans = 0;
// Traverse array elements
for (int i = 0; i < n; i++)
{
// already swapped and corrected or
// already present at correct pos
if (vis[i] || arrPos[i].second == i)
continue;
// find out the number of node in
// this cycle and add in ans
int cycle_size = 0;
int j = i;
while (!vis[j])
{
vis[j] = 1;
// move to next node
1460
Chapter 218. Minimum swaps to make two arrays identical
j = arrPos[j].second;
cycle_size++;
}
// Update answer by adding current cycle.
ans += (cycle_size - 1);
}
// Return result
return ans;
}
// method returns minimum number of swap to make
// array B same as array A
int minSwapToMakeArraySame(int a[], int b[], int n)
{
// map to store position of elements in array B
// we basically store element to index mapping.
map<int, int> mp;
for (int i = 0; i < n; i++)
mp[b[i]] = i;
// now we're storing position of array A elements
// in array B.
for (int i = 0; i < n; i++)
b[i] = mp[a[i]];
/* We can uncomment this section to print modified
b array
for (int i = 0; i < N; i++)
cout << b[i] << " ";
cout << endl; */
// returing minimum swap for sorting in modified
// array B as final answer
return minSwapsToSort(b, n);
}
// Driver code to test above methods
int main()
{
int a[] = {3, 6, 4, 8};
int b[] = {4, 6, 8, 3};
int n = sizeof(a) / sizeof(int);
cout << minSwapToMakeArraySame(a, b, n);
return 0;
}
1461
Chapter 218. Minimum swaps to make two arrays identical
Output:
Source
https://www.geeksforgeeks.org/minimum-swaps-to-make-two-array-identical/
1462
Chapter 219
Minimum swaps to reach permuted array with at most 2 positions left swaps allowed -
GeeksforGeeks
Given a permuted array of length N of first N natural numbers, we need to tell the minimum
number of swaps required in the sorted array of first N natural number to reach given
permuted array where a number can be swapped with at most 2 positions left to it. If it is
not possible to reach permuted array by above swap condition then print not possible.
Examples:
We can solve this problem using inversions. As we can see that if a number is at a position
which is more than 2 places away from its actual position then it is not possible to reach there
just by swapping with elements at 2 left positions and if all element satisfy this property
(there are <=2 elements smaller than it on the right) then answer will simply be total
1463
Chapter 219. Minimum swaps to reach permuted array with at most 2 positions left swaps
allowed
number of inversions in the array because that many swaps will be needed to transform the
array into permuted array.
We can find the number of inversions in N log N time using merge sort technique explained
here so total time complexity of solution will be O(N log N) only.
1464
Chapter 219. Minimum swaps to reach permuted array with at most 2 positions left swaps
allowed
1465
Chapter 219. Minimum swaps to reach permuted array with at most 2 positions left swaps
allowed
return -1;
}
/* If permuted array is not Invalid, then number
of Inversion in array will be our final answer */
int numOfInversion = mergeSort(arr, N);
return numOfInversion;
}
// Driver code to test above methods
int main()
{
// change below example
int arr[] = {1, 2, 5, 3, 4};
int N = sizeof(arr) / sizeof(int);
int res = minSwapToReachArr(arr, N);
if (res == -1)
cout << "Not Possible\n";
else
cout << res << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/minimum-swaps-reach-permuted-array-2-positions-left-swaps-allowed/
1466
Chapter 220
A simple solution is to run two loops. The outer loop picks all elements one by one. The
inner loop finds frequency of the picked element and compares with the maximum so far.
Time complexity of this solution is O(n2 )
A better solution is to do sorting. We first sort the array, then linearly traverse the array.
C++
1467
Chapter 220. Most frequent element in an array
Java
1468
Chapter 220. Most frequent element in an array
Arrays.sort(arr);
// find the max frequency using linear
// traversal
int max_count = 1, res = arr[0];
int curr_count = 1;
for (int i = 1; i < n; i++)
{
if (arr[i] == arr[i - 1])
curr_count++;
else
{
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is most frequent
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[n - 1];
}
return res;
}
// Driver program
public static void main (String[] args) {
int arr[] = {1, 5, 2, 1, 3, 2, 1};
int n = arr.length;
System.out.println(mostFrequent(arr,n));
}
}
// This code is contributed by Akash Singh.
Python3
1469
Chapter 220. Most frequent element in an array
C#
1470
Chapter 220. Most frequent element in an array
PHP
1471
Chapter 220. Most frequent element in an array
<?php
// PHP program to find the
// most frequent element
// in an array.
function mostFrequent( $arr, $n)
{
// Sort the array
sort($arr);
sort($arr , $n);
// find the max frequency
// using linear traversal
$max_count = 1;
$res = $arr[0];
$curr_count = 1;
for ($i = 1; $i < $n; $i++)
{
if ($arr[$i] == $arr[$i - 1])
$curr_count++;
else
{
if ($curr_count > $max_count)
{
$max_count = $curr_count;
$res = $arr[$i - 1];
}
$curr_count = 1;
}
}
// If last element
// is most frequent
if ($curr_count > $max_count)
{
$max_count = $curr_count;
$res = $arr[$n - 1];
}
return $res;
}
// Driver Code
{
$arr = array(1, 5, 2, 1, 3, 2, 1);
$n = sizeof($arr) / sizeof($arr[0]);
echo mostFrequent($arr, $n);
1472
Chapter 220. Most frequent element in an array
return 0;
}
// This code is contributed by nitin mittal
?>
Output :
1473
Chapter 220. Most frequent element in an array
Java
1474
Chapter 220. Most frequent element in an array
return res;
}
// Driver code
public static void main (String[] args) {
int arr[] = {1, 5, 2, 1, 3, 2, 1};
int n = arr.length;
System.out.println(mostFrequent(arr, n));
}
}
// This code is contributed by Akash Singh.
C#
1475
Chapter 220. Most frequent element in an array
Output:
Source
https://www.geeksforgeeks.org/frequent-element-array/
1476
Chapter 221
A simple solution is to run two loops and count occurrences of every word. Time com-
plexity of this solution is O(n * n * MAX_WORD_LEN).
An efficient solution is to use Trie data structure. The idea is simple first we will insert
in trie. In trie, we keep counts of words ending at a node. We do preorder traversal and
compare count present at each node and find the maximum occurring word
1477
Chapter 221. Most frequent word in an array of strings
string key;
int cnt;
unordered_map<char, Trie*> map;
};
/* Function to return a new Trie node */
Trie* getNewTrieNode()
{
Trie* node = new Trie;
node->cnt = 0;
return node;
}
/* function to insert a string */
void insert(Trie*& root, string &str)
{
// start from root node
Trie* temp = root;
for (int i=0; i<str.length(); i++) {
char x = str[i];
/*a new node if path doesn't exists*/
if (temp->map.find(x) == temp->map.end())
temp->map[x] = getNewTrieNode();
// go to next node
temp = temp->map[x];
}
// store key and its count in leaf nodes
temp->key = str;
temp->cnt += 1;
}
/* function for preorder traversal */
bool preorder(Trie* temp, int& maxcnt, string& key)
{
if (temp == NULL)
return false;
for (auto it : temp->map) {
/*leaf node will have non-zero count*/
if (maxcnt < it.second->cnt) {
key = it.second->key;
maxcnt = it.second->cnt;
1478
Chapter 221. Most frequent word in an array of strings
}
// recurse for current node children
preorder(it.second, maxcnt, key);
}
}
void mostFrequentWord(string arr[], int n)
{
// Insert all words in a Trie
Trie* root = getNewTrieNode();
for (int i = 0; i < n; i++)
insert(root, arr[i]);
// Do preorder traversal to find the
// most frequent word
string key;
int cnt = 0;
preorder(root, cnt, key);
cout << "The word that occurs most is : "
<< key << endl;
cout << "No of times: " << cnt << endl;
}
// Driver code
int main()
{
// given set of keys
string arr[] = {"geeks", "for", "geeks", "a",
"portal", "to", "learn", "can", "be",
"computer", "science", "zoom", "yup",
"fire", "in", "be", "data", "geeks"};
int n = sizeof(arr) / sizeof(arr[0]);
mostFrequentWord(arr, n);
return 0;
}
Output:
1479
Chapter 221. Most frequent word in an array of strings
Another efficient solution is to use hashing. Please refer Find winner of an election
where votes are represented as candidate names for details.
Source
https://www.geeksforgeeks.org/frequent-word-array-strings/
1480
Chapter 222
Since the elements are as large as 10^9 we cannot use direct index table.
One solution is to sort both multisets and compare them one by one.
1481
Chapter 222. Multiset Equivalence Problem
Output:
No
A better solution is to use hashing. We create two empty hash tables (implemented using
unordered_map in C++). We first insert all items of first multimap in first table and all
items of second multiset in second table. Now we check if both hash tables contain same
items and frequencies or not.
1482
Chapter 222. Multiset Equivalence Problem
// Now we check if both unordered_maps
// are same of not.
for (auto x : m1) {
if (m2.find(x.first) == m2.end() ||
m2[x.first] != x.second)
return false;
}
return true;
}
// Driver code
int main()
{
vector<int> a({ 7, 7, 5 }), b({ 7, 7, 5 });
if (areSame(a, b))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}
Output:
Yes
Time complexity : O(n) under the assumption that unordered_map find() and insert()
operations work in O(1) time.
Source
https://www.geeksforgeeks.org/multiset-equivalence-problem/
1483
Chapter 223
No of pairs (a[j] >= a[i]) with k numbers in range (a[i], a[j]) that are divisible by x -
GeeksforGeeks
Given an array and two numbers x and k. Find the number of different ordered pairs of
indexes (i, j) such that a[j] >= a[i] and there are exactly k integers num such that num is
divisible by x and num is in range a[i]-a[j].
Examples:
A naive approach is to traverse through all pairs possible and count the number of pairs
that have k integers in between them which are divisible by x.
Time complexity: O(n^2)
1484
Chapter 223. No of pairs (a[j] >= a[i]) with k numbers in range (a[i], a[j]) that are
divisible by x
An efficient approach is to sort the array and use binary search to find out the right
and left boundaries of numbers(use lower_bound function inbuilt function to do it) which
satisfy the condition and which do not. We have to sort the array as it is given every pair
should be a[j] >= a[i] irrespective of value of i and j. After sorting we traverse through
n elements, and find the number with whose multiplication with x gives a[i]-1, so that we
can find k number by adding k to d = a[i]-1/x. So we binary search for the value (d+k)*x
to get the multiple with which we can make a pair of a[i] as it will have exactly k integers
in between a[i] and a[j]. In this way we get the left boundary for a[j] using binary search
in O(log n), and for all other pairs possible with a[i], we need to find out the right-most
boundary by searching the the number equal to or greater then (d+k+1)*x where we will
get k+1 multiples and we get the no of pairs as (right-left) boundary [index-wise].
1485
Chapter 223. No of pairs (a[j] >= a[i]) with k numbers in range (a[i], a[j]) that are
divisible by x
{
int a[] = { 1, 3, 5, 7 };
int n = sizeof(a) / sizeof(a[0]);
int x = 2, k = 1;
// function call to get the number of pairs
cout << countPairs(a, n, x, k);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/no-pairs-aj-ai-k-numbers-range-ai-aj-divisible-x/
1486
Chapter 224
1487
Chapter 224. Noble integers in an array (count of greater elements is equal to value)
Java
1488
Chapter 224. Noble integers in an array (count of greater elements is equal to value)
{
int size = arr.length;
for (int i = 0; i < size; i++ )
{
int count = 0;
for (int j = 0; j < size; j++)
if (arr[i] < arr[j])
count++;
// If count of greater elements
// is equal to arr[i]
if (count == arr[i])
return arr[i];
}
return -1;
}
// Driver code
public static void main(String args[])
{
int [] arr = {10, 3, 20, 40, 2};
int res = nobleInteger(arr);
if (res != -1)
System.out.println("The noble "
+ "integer is "+ res);
else
System.out.println("No Noble "
+ "Integer Found");
}
}
Python3
1489
Chapter 224. Noble integers in an array (count of greater elements is equal to value)
# to arr[i]
if (count == arr[i]):
return arr[i]
return -1
# Driver code
arr = [10, 3, 20, 40, 2]
size = len(arr)
res = nobleInteger(arr,size)
if (res != -1):
print("The noble integer is ",
res)
else:
print("No Noble Integer Found")
# This code is contributed by
# Smitha.
C#
1490
Chapter 224. Noble integers in an array (count of greater elements is equal to value)
PHP
<?php
// PHP program to find Noble
// elements in an array.
// Returns a Noble integer
// if present, else returns -1.
function nobleInteger( $arr, $size)
{
for ( $i = 0; $i < $size; $i++ )
{
$count = 0;
for ( $j = 0; $j < $size; $j++)
if ($arr[$i] < $arr[$j])
$count++;
// If count of greater elements
// is equal to arr[i]
if ($count == $arr[$i])
return $arr[$i];
}
return -1;
}
// Driver code
$arr = array(10, 3, 20, 40, 2);
$size = count($arr);
$res = nobleInteger($arr, $size);
if ($res != -1)
1491
Chapter 224. Noble integers in an array (count of greater elements is equal to value)
Output :
1. Sort the Array arr[] in ascending order. This step takes (O(nlogn)).
2. Iterate through the array. Compare the value of index i to the number of elements
after index i. If arr[i] equals the number of elements after arr[i], it is a noble Integer.
Condition to check: (A[i] == length-i-1). This step takes O(n).
Note: Array may have duplicate elements. So, we should skip the elements (adjacent
elements in the sorted array) that are same.
Java
1492
Chapter 224. Noble integers in an array (count of greater elements is equal to value)
C#
1493
Chapter 224. Noble integers in an array (count of greater elements is equal to value)
if (arr[n-1] == 0)
return arr[n-1];
return -1;
}
// Driver code
static public void Main ()
{
int [] arr = {10, 3, 20, 40, 2};
int res = nobleInteger(arr);
if (res != -1)
Console.Write("The noble integer is "
+ res);
else
Console.Write("No Noble Integer "
+ "Found");
}
}
// This code is contributed by Shrikant13.
PHP
<?php
// PHP program to find Noble elements
// Returns a Noble integer if present,
// else returns -1.
function nobleInteger( $arr)
{
sort($arr);
// Return a Noble element if
// present before last.
$n = count($arr);
for ( $i = 0; $i < $n - 1; $i++)
{
if ($arr[$i] == $arr[$i + 1])
continue;
// In case of duplicates, we
// reach last occurrence here.
if ($arr[$i] == $n - $i - 1)
return $arr[$i];
}
1494
Chapter 224. Noble integers in an array (count of greater elements is equal to value)
if ($arr[$n - 1] == 0)
return $arr[$n - 1];
return -1;
}
// Driver code
$arr = array(10, 3, 20, 40, 2);
$res = nobleInteger($arr);
if ($res != -1)
echo "The noble integer is ", $res;
else
echo "No Noble Integer Found";
// This code is contributed by anuj_67.
?>
Output :
Source
https://www.geeksforgeeks.org/noble-integers-in-an-array-count-of-greater-elements-is-equal-to-value/
1495
Chapter 225
Number of elements greater than K in the range L to R using Fenwick Tree (Offline queries)
- GeeksforGeeks
Prerequisites: Fenwick Tree (Binary Indexed Tree)
Given an array of N numbers, and a number of queries where each query will contain three
numbers(l, r and k). The task is to calculate the number of array elements which are greater
than K in the subarray[L, R].
Examples:
Input: n=6
q=2
arr[ ] = { 7, 3, 9, 13, 5, 4 }
Query1: l=1, r=4, k=6
Query2: l=2, r=6, k=8
Output: 3
2
1496
Chapter 225. Number of elements greater than K in the range L to R using Fenwick Tree
(Offline queries)
Naive Approach is to find the answer for each query by simply traversing the array from
index l till r and keep adding 1 to the count whenever the array element is greater than k.
Time Complexity: O(n*q)
A Better Approach is to use Merge Sort Tree. In this approach, build a Segment Tree
with a vector at each node containing all the elements of the sub-range in a sorted order.
Answer each query using the segment tree where Binary Search can be used to calculate
how many numbers are present in each node whose sub-range lies within the query range
which are greater than k.
Time complexity: O(q * log(n) * log(n))
An Efficient Approach is to solve the problem using offline queries and Fenwick Trees.
Below are the steps:
• First store all the array elements and the queries in the same array. For this, we can
create a self-structure or class.
• Then sort the structural array in descending order ( in case of collision the query will
come first then the array element).
• Process the whole array of structure again, but before that create another BIT array
(Binary Indexed Tree) whose query( i ) function will return the count of all the elements
which are present in the array till i’th index.
• If it is an array element, then update the BIT array with +1 from the index of that
element.
• If it is a query, then subtract the query(r) – query(l-1) and this will be the answer
for that query which will be stored in answer array at the index corresponding to the
query number.
The key observation here is that since the array of the structure has been sorted in descending
order. Whenever we encounter any query only the elements which are greater than ‘k’
comprises the count in the BIT array which is the answer that is needed.
Below is the explanation of structure used in the program:
1497
Chapter 225. Number of elements greater than K in the range L to R using Fenwick Tree
(Offline queries)
1498
Chapter 225. Number of elements greater than K in the range L to R using Fenwick Tree
(Offline queries)
{
int ans = 0;
while (idx) {
ans += BIT[idx];
idx -= idx & (-idx);
}
return ans;
}
// Function to solve the queries offline
void solveQuery(int arr[], int n, int QueryL[],
int QueryR[], int QueryK[], int q)
{
// create node to store the elements
// and the queries
node a[n + q + 1];
// 1-based indexing.
// traverse for all array numbers
for (int i = 1; i <= n; ++i) {
a[i].val = arr[i - 1];
a[i].pos = 0;
a[i].l = 0;
a[i].r = i;
}
// iterate for all queries
for (int i = n + 1; i <= n + q; ++i) {
a[i].pos = i - n;
a[i].val = QueryK[i - n - 1];
a[i].l = QueryL[i - n - 1];
a[i].r = QueryR[i - n - 1];
}
// In-built sort function used to
// sort node array using comp function.
sort(a + 1, a + n + q + 1, comp);
// Binary Indexed tree with
// initially 0 at all places.
int BIT[n + 1];
// initially 0
memset(BIT, 0, sizeof(BIT));
// For storing answers for each query( 1-based indexing ).
int ans[q + 1];
1499
Chapter 225. Number of elements greater than K in the range L to R using Fenwick Tree
(Offline queries)
// traverse for numbers and query
for (int i = 1; i <= n + q; ++i) {
if (a[i].pos != 0) {
// call function to returns answer for each query
int cnt = query(BIT, a[i].r) - query(BIT, a[i].l - 1);
// This will ensure that answer of each query
// are stored in order it was initially asked.
ans[a[i].pos] = cnt;
}
else {
// a[i].r contains the position of the
// element in the original array.
update(BIT, n, a[i].r);
}
}
// Output the answer array
for (int i = 1; i <= q; ++i) {
cout << ans[i] << endl;
}
}
// Driver Code
int main()
{
int arr[] = { 7, 3, 9, 13, 5, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// 1-based indexing
int QueryL[] = { 1, 2 };
int QueryR[] = { 4, 6 };
// k for each query
int QueryK[] = { 6, 8 };
// number of queries
int q = sizeof(QueryL) / sizeof(QueryL[0]);
// Function call to get
solveQuery(arr, n, QueryL, QueryR, QueryK, q);
return 0;
}
Output:
1500
Chapter 225. Number of elements greater than K in the range L to R using Fenwick Tree
(Offline queries)
3
2
Source
https://www.geeksforgeeks.org/number-of-elements-greater-than-k-in-the-range-l-to-r-using-fenwick-tree-offline-qu
1501
Chapter 226
Examples:
1502
Chapter 226. Number of paths from source to destination in a directed acyclic graph
Approach : Let f(u) be the number of ways one can travel from node u to destination vertex.
Hence, f(source) is required answer. As f(destination) = 1 here so there is just one path
from destination to itself. One can observe, f(u) depends on nothing other than the f values
of all the nodes which are possible to travel from u. It makes sense because the number of
different paths from u to the destination is the sum of all different paths from v1, v2, v3…
v-n to destination vertex where v1 to v-n are all the vertices that have a direct path from
vertex u. This approach, however, is too slow to be useful. Each function call branches out
into further calls, and that branches into further calls, until each and every path is explored
once.
The problem with this approach is the calculation of f(u) again and again each time the func-
tion is called with argument u. Since this problem exhibits both overlapping subproblems
and optimal substructure, dynamic programming is applicable here. In order to evaluate
f(u) for each u just once, evaluate f(v) for all v that can be visited from u before evaluating
f(u). This condition is satisfied by reverse topological sorted order of the nodes of the graph.
Below is the implementation of the above approach:
1503
Chapter 226. Number of paths from source to destination in a directed acyclic graph
{
queue<int> q;
// insert all vertices which
// don't have any parent.
for (int i = 0; i < n; i++)
if (!fre[i])
q.push(i);
vector<int> l;
// using kahn's algorithm
// for topological sorting
while (!q.empty()) {
int u = q.front();
q.pop();
// insert front element of queue to vector
l.push_back(u);
// go through all it's childs
for (int i = 0; i < v[u].size(); i++) {
fre[v[u][i]]--;
// whenever the freqency is zero then add
// this vertex to queue.
if (!fre[v[u][i]])
q.push(v[u][i]);
}
}
return l;
}
// Function that returns the number of paths
int numberofPaths(int source, int destination, int n, int fre[])
{
// make topological sorting
vector<int> s = topological_sorting(fre, n);
// to store required answer.
int dp[n] = { 0 };
// answer from destination
// to destination is 1.
dp[destination] = 1;
// traverse in reverse order
1504
Chapter 226. Number of paths from source to destination in a directed acyclic graph
Output:
Source
https://www.geeksforgeeks.org/number-of-paths-from-source-to-destination-in-a-directed-acyclic-graph/
1505
Chapter 227
a * b + c - e = f
d
Examples:
Input : arr[] = { 1 }.
Output : 1
a = b = c = d = e = f = 1 satisfy
the equation.
Input : arr[] = { 2, 3 }
Output : 4
Input : arr[] = { 1, -1 }
Output : 24
1506
Chapter 227. Number of sextuplets (or six values) that satisfy an equation
1507
Chapter 227. Number of sextuplets (or six values) that satisfy an equation
Output:
Source
https://www.geeksforgeeks.org/number-sextuplets-six-values-satisfy-equation/
1508
Chapter 228
)
There is an interesting solution to this problem. It can be solved using the fact that number
of swaps needed is equal to number of inversions. So we basically need to count inversions
in array.
The fact can be established using below observations:
1) A sorted array has no inversions.
2) An adjacent swap can reduce one inversion. Doing x adjacent swaps can reduce x inver-
sions in an array.
C++
1509
Chapter 228. Number of swaps to sort when only adjacent swapping allowed
1510
Chapter 228. Number of swaps to sort when only adjacent swapping allowed
{
int mid, inv_count = 0;
if (right > left)
{
/* Divide the array into two parts and call
_mergeSortAndCountInv() for each of the parts */
mid = (right + left)/2;
/* Inversion count will be sum of inversions in
left-part, right-part and number of inversions
in merging */
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid+1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid+1, right);
}
return inv_count;
}
/* This function sorts the input array and returns the
number of inversions in the array */
int countSwaps(int arr[], int n)
{
int temp[n];
return _mergeSort(arr, temp, 0, n - 1);
}
/* Driver progra to test above functions */
int main(int argv, char** args)
{
int arr[] = {1, 20, 6, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Number of swaps is %d \n", countSwaps(arr, n));
return 0;
}
Java
1511
Chapter 228. Number of swaps to sort when only adjacent swapping allowed
1512
Chapter 228. Number of swaps to sort when only adjacent swapping allowed
// An auxiliary recursive function that
// sorts the input array and returns
// the number of inversions in the array.
static int _mergeSort(int arr[], int temp[],
int left, int right)
{
int mid, inv_count = 0;
if (right > left)
{
// Divide the array into two parts and
// call _mergeSortAndCountInv() for
// each of the parts
mid = (right + left)/2;
/* Inversion count will be sum of
inversions in left-part, right-part
and number of inversions in merging */
inv_count = _mergeSort(arr, temp,
left, mid);
inv_count += _mergeSort(arr, temp,
mid+1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp,
left, mid+1, right);
}
return inv_count;
}
// This function sorts the input
// array and returns the number
// of inversions in the array
static int countSwaps(int arr[], int n)
{
int temp[] = new int[n];
return _mergeSort(arr, temp, 0, n - 1);
}
// Driver Code
public static void main (String[] args)
{
int arr[] = {1, 20, 6, 4, 5};
int n = arr.length;
System.out.println("Number of swaps is "
1513
Chapter 228. Number of swaps to sort when only adjacent swapping allowed
C#
1514
Chapter 228. Number of swaps to sort when only adjacent swapping allowed
1515
Chapter 228. Number of swaps to sort when only adjacent swapping allowed
/*Merge the two parts*/
inv_count += merge(arr, temp,
left, mid + 1, right);
}
return inv_count;
}
// This function sorts the input
// array and returns the number
// of inversions in the array
static int countSwaps(int []arr, int n)
{
int []temp = new int[n];
return _mergeSort(arr, temp, 0, n - 1);
}
// Driver Code
public static void Main ()
{
int []arr = {1, 20, 6, 4, 5};
int n = arr.Length;
Console.Write("Number of swaps is " +
countSwaps(arr, n));
}
}
// This code is contributed by nitin mittal.
Output :
Number of swaps is 5
References :
http://stackoverflow.com/questions/20990127/sorting-a-sequence-by-swapping-adjacent-elements-using-minimum-s
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/number-swaps-sort-adjacent-swapping-allowed/
1516
Chapter 229
Input : arr[] = { 1, 3, 4, 5 }
Output : 3
Put box of size 1 in box of size 3.
Input : arr[] = { 4, 2, 1, 8 }
Output : 1
Put box of size 1 in box of size 2
and box of size 2 in box of size 4.
And put box of size 4 in box of size 8.
The idea is to sort the array. Now, make a queue and insert first element of sorted array.
Now traverse the array from first element and insert each element in the queue, also check
if front element of queue is less than or equal to half of current traversed element. So, the
number of visible box will be number of element in queue after traversing the sorted array.
Basically, we are trying to put a box of size in smallest box which is greater than or equal
to 2*x.
For example, if arr[] = { 2, 3, 4, 6 }, then we trying to put box of size 2 in box of size 4
instead of box of size 6 because if we put box of size 2 in box of size 6 then box of size 3
cannot be kept in any other box and we need to minimize the number of visible box.
C++
1517
Chapter 229. Number of visible boxes after putting one inside another
Java
1518
Chapter 229. Number of visible boxes after putting one inside another
import java.util.Arrays;
public class GFG {
// return the minimum number of visible
// boxes
static int minimumBox(int []arr, int n)
{
// New Queue of integers.
Queue<Integer> q = new LinkedList<>();
// sorting the array
Arrays.sort(arr);
q.add(arr[0]);
// traversing the array
for (int i = 1; i < n; i++)
{
int now = q.element();
// checking if current element
// is greater than or equal to
// twice of front element
if (arr[i] >= 2 * now)
q.remove();
// Pushing each element of array
q.add(arr[i]);
}
return q.size();
}
// Driver code
public static void main(String args[])
{
int [] arr = { 4, 1, 2, 8 };
int n = arr.length;
System.out.println(minimumBox(arr, n));
}
}
// This code is contributed by Sam007.
C#
1519
Chapter 229. Number of visible boxes after putting one inside another
1520
Chapter 229. Number of visible boxes after putting one inside another
Output –
Source
https://www.geeksforgeeks.org/number-visible-boxes-putting-one-inside-another/
1521
Chapter 230
1522
Chapter 230. Odd-Even Sort / Brick Sort
// Perform Bubble sort on even indexed element
for (int i=0; i<=n-2; i=i+2)
{
if (arr[i] > arr[i+1])
{
swap(arr[i], arr[i+1]);
isSorted = false;
}
}
}
return;
}
// A utility function ot print an array of size n
void printArray(int arr[], int n)
{
for (int i=0; i < n; i++)
cout << arr[i] << " ";
cout << "\n";
}
// Driver program to test above functions.
int main()
{
int arr[] = {34, 2, 10, -9};
int n = sizeof(arr)/sizeof(arr[0]);
oddEvenSort(arr, n);
printArray(arr, n);
return (0);
}
Java
1523
Chapter 230. Odd-Even Sort / Brick Sort
{
isSorted = true;
int temp =0;
// Perform Bubble sort on odd indexed element
for (int i=1; i<=n-2; i=i+2)
{
if (arr[i] > arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
isSorted = false;
}
}
// Perform Bubble sort on even indexed element
for (int i=0; i<=n-2; i=i+2)
{
if (arr[i] > arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
isSorted = false;
}
}
}
return;
}
public static void main (String[] args)
{
int arr[] = {34, 2, 10, -9};
int n = arr.length;
oddEvenSort(arr, n);
for (int i=0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println(" ");
}
}
// Code Contribute by Mohit Gupta_OMG <(0_o)>
Python3
1524
Chapter 230. Odd-Even Sort / Brick Sort
C#
// C# Program to implement
// Odd-Even / Brick Sort
using System;
class GFG
{
public static void oddEvenSort(int []arr, int n)
{
// Initially array is unsorted
bool isSorted = false;
while (!isSorted)
{
isSorted = true;
int temp =0;
1525
Chapter 230. Odd-Even Sort / Brick Sort
Output :
1526
Chapter 230. Odd-Even Sort / Brick Sort
-9 2 10 34
We demonstrate the above algorithm using the below illustration on the array = {3, 2, 3, 8,
5, 6, 4, 1}
1527
Chapter 230. Odd-Even Sort / Brick Sort
Source
https://www.geeksforgeeks.org/odd-even-sort-brick-sort/
1528
Chapter 231
If you are trying to sort the array of string in a simple manner you can simple create a
comparison function for character comparison and sort the given array of strings. But that
will differentiate lower case and upper case alphabets. To solve this problem if you are otping
to solve this in c/java you have to write your own comparision function which specially take
care of cases of alphabets. But if we will opt PHP as our language then we can sort it
directly with the help of natcasesort().
natcasesort() : It sort strings regardless of their case. Means ‘a’ & ‘A’ are treated smaller
than ‘b’ & ‘B’ in this sorting method.
// declare array
$arr = array ("Hello", "to", "geeks", "for", "GEEks");
// Standard sort
$standard_result = sort($arr);
1529
Chapter 231. PHP Sort array of strings in natural and standard orders
print_r($standart_result);
// natural sort
$natural_result = natcasesort($arr);
print_r($natural_result);
<?php
// PHP program to sort an array
// in standard and natural ways.
// function to print array
function printArray ($arr)
{
foreach ($arr as $value) {
echo "$value ";
}
}
// declare array
$arr = array ("Hello", "to", "geeks", "for", "GEEks");
// Standard sort
$standard_result = $arr;
sort($standard_result);
echo "Array after Standard sorting: ";
printArray($standard_result);
// natural sort
$natural_result = $arr;
natcasesort($natural_result);
echo "\nArray after Natural sorting: ";
printArray($natural_result);
?>
Output:
Source
https://www.geeksforgeeks.org/php-sort-array-strings-natural-standard-orders/
1530
Chapter 232
Input : N = 2
arr[] = { 5, 8, 3, 9 }
Output : (3, 9) (5, 8)
Explanation:
Possible pairs are :
1. (8, 9) (3, 5) Maximum Sum of a Pair = 17
2. (5, 9) (3, 8) Maximum Sum of a Pair = 14
3. (3, 9) (5, 8) Maximum Sum of a Pair = 13
Thus, in case 3, the maximum pair sum is minimum of all the other cases. Hence,
the answer is(3, 9) (5, 8).
Input : N = 2
arr[] = { 9, 6, 5, 1 }
Output : (1, 9) (5, 6)
Approach: The idea is to first sort the given array and then iterate over the loop to form
pairs (i, j) where i would start from 0 and j would start from end of array correspondingly.
Increment i and Decrement j to form the next pair and so on.
Below is the implementation of above approach.
C++
1531
Chapter 232. Pair formation such that maximum pair sum is minimized
Java
1532
Chapter 232. Pair formation such that maximum pair sum is minimized
// Driver Code
public static void main (String[] args)
{
int arr[] = {9, 6, 5, 1};
int N = arr.length;
findOptimalPairs(arr, N);
}
}
// This code is contributed by anuj_67.
Output:
(1, 9) (5, 6)
Improved By : vt_m
Source
https://www.geeksforgeeks.org/pair-formation-maximum-pair-sum-minimized/
1533
Chapter 233
To solve this problem, we first sort the given array and then for each element Ai, we find
number of elements equal to value Ai * k^x for different value of x till Ai * k^x is less than
or equal to largest of Ai.
Algorithm:
1534
Chapter 233. Pairs such that one is a power multiple of other
C++
1535
Chapter 233. Pairs such that one is a power multiple of other
x++;
}
}
}
return ans;
}
// driver program
int main() {
int A[] = {3, 8, 9, 12, 18, 4, 24, 2, 6};
int n = sizeof(A) / sizeof(A[0]);
int k = 3;
cout << countPairs(A, n, k);
return 0;
}
Java
1536
Chapter 233. Pairs such that one is a power multiple of other
x++;
}
}
}
return ans;
}
// Driver program
public static void main (String[] args)
{
int A[] = {3, 8, 9, 12, 18, 4, 24, 2, 6};
int n = A.length;
int k = 3;
System.out.println (countPairs(A, n, k));
}
}
// This code is contributed by vt_m.
Python3
1537
Chapter 233. Pairs such that one is a power multiple of other
# driver program
A = [3, 8, 9, 12, 18, 4, 24, 2, 6]
n = len(A)
k = 3
print(countPairs(A, n, k))
# This code is contributed by
# Smitha Dinesh Semwal
C#
1538
Chapter 233. Pairs such that one is a power multiple of other
}
// Driver program
public static void Main ()
{
int []A = {3, 8, 9, 12, 18, 4, 24, 2, 6};
int n = A.Length;
int k = 3;
Console.WriteLine(countPairs(A, n, k));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to find pairs count
// function to count
// the required pairs
function countPairs($A, $n, $k)
{
$ans = 0;
// sort the given array
sort($A);
// for each A[i]
// traverse rest array
for ($i = 0; $i < $n; $i++)
{
for ($j = $i + 1; $j < $n; $j++)
{
// count Aj such that Ai*k^x = Aj
$x = 0;
// increase x till Ai *
// k^x <= largest element
while (($A[$i] * pow($k, $x)) <= $A[$j])
{
if (($A[$i] * pow($k, $x)) == $A[$j])
{
$ans++;
break;
}
1539
Chapter 233. Pairs such that one is a power multiple of other
$x++;
}
}
}
return $ans;
}
// Driver Code
$A = array(3, 8, 9, 12, 18,
4, 24, 2, 6);
$n = count($A);
$k = 3;
echo countPairs($A, $n, $k);
// This code is contributed by anuj_67.
?>
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/pairs-one-power-multiple/
1540
Chapter 234
Method 1 (Simple) : Run two nested loops. The outer loop picks every element x one by
one. The inner loop considers all elements after x and checks if difference is within limits or
not.
C++
1541
Chapter 234. Pairs with Difference less than K
Java
1542
Chapter 234. Pairs with Difference less than K
}
// This code is contributed by vt_m.
Python3
C#
1543
Chapter 234. Pairs with Difference less than K
PHP
<?php
// PHP code to find count of Pairs
// with difference less than K.
function countPairs( $a, $n, $k)
{
$res = 0;
for($i = 0; $i < $n; $i++)
for($j = $i + 1; $j < $n; $j++)
if (abs($a[$j] - $a[$i]) < $k)
$res++;
return $res;
}
// Driver code
$a = array(1, 10, 4, 2);
$k = 3;
$n = count($a);
echo countPairs($a, $n, $k);
// This code is contributed by anuj_67.
?>
Output :
1544
Chapter 234. Pairs with Difference less than K
Java
1545
Chapter 234. Pairs with Difference less than K
Python3
1546
Chapter 234. Pairs with Difference less than K
j = i+1
while (j < n and a[j] - a[i] < k):
res += 1
j += 1
return res
# Driver code
a = [1, 10, 4, 2]
k = 3
n = len(a)
print(countPairs(a, n, k), end = "")
# This code is contributed by Azkia Anam.
C#
1547
Chapter 234. Pairs with Difference less than K
PHP
<?php
// PHP code to find count of
// Pairs with difference less than K.
function countPairs( $a, $n, $k)
{
// to sort the array.
sort($a);
$res = 0;
for ( $i = 0; $i < $n; $i++)
{
// Keep incrementing result
// while subsequent elements
// are within limits.
$j = $i + 1;
while ($j < $n and
$a[$j] - $a[$i] < $k)
{
$res++;
$j++;
}
}
return $res;
}
// Driver code
$a = array(1, 10, 4, 2);
$k = 3;
$n = count($a);
echo countPairs($a, $n, $k);
// This code is contributed by anuj_67.
?>
1548
Chapter 234. Pairs with Difference less than K
Output :
Time complexity : O(res) where res is number of pairs in output. Note that in worst
case this also takes O(n2 ) time but works much better in general.
Improved By : vt_m
Source
https://www.geeksforgeeks.org/pairs-difference-less-k/
1549
Chapter 235
Pancake sorting
Unlike a traditional sorting algorithm, which attempts to sort with the fewest comparisons
possible, the goal is to sort the sequence in as few reversals as possible.
The idea is to do something similar to Selection Sort. We one by one place maximum
element at the end and reduce the size of current array by one.
Following are the detailed steps. Let given array be arr[] and size of array be n.
1) Start from current size equal to n and reduce current size by one while it’s greater than
1. Let the current size be curr_size. Do following for every curr_size
……a) Find index of the maximum element in arr[0..curr_szie-1]. Let the index be ‘mi’
……b) Call flip(arr, mi)
……c) Call flip(arr, curr_size-1)
See following video for visualization of the above algorithm.
http://www.youtube.com/embed/kk-_DDgoXfk
C
// C program to
// sort array using
// pancake sort
#include <stdlib.h>
#include <stdio.h>
/* Reverses arr[0..i] */
1550
Chapter 235. Pancake sorting
1551
Chapter 235. Pancake sorting
Java
// Java program to
// sort array using
// pancake sort
import java.io.*;
class PancakeSort {
/* Reverses arr[0..i] */
static void flip(int arr[], int i)
{
int temp, start = 0;
1552
Chapter 235. Pancake sorting
1553
Chapter 235. Pancake sorting
Python3
# Python3 program to
# sort array using
# pancake sort
# Reverses arr[0..i] */
def flip(arr, i):
start = 0
while start < i:
temp = arr[start]
arr[start] = arr[i]
arr[i] = temp
start += 1
i -= 1
# Returns index of the maximum
1554
Chapter 235. Pancake sorting
# element in arr[0..n-1] */
def findMax(arr, n):
mi = 0
for i in range(0,n):
if arr[i] > arr[mi]:
mi = i
return mi
# The main function that
# sorts given array
# using flip operations
def pancakeSort(arr, n):
# Start from the complete
# array and one by one
# reduce current size
# by one
curr_size = n
while curr_size > 1:
# Find index of the maximum
# element in
# arr[0..curr_size-1]
mi = findMax(arr, curr_size)
# Move the maximum element
# to end of current array
# if it's not already at
# the end
if mi != curr_size-1:
# To move at the end,
# first move maximum
# number to beginning
flip(arr, mi)
# Now move the maximum
# number to end by
# reversing current array
flip(arr, curr_size-1)
curr_size -= 1
# A utility function to
# print an array of size n
def printArray(arr, n):
for i in range(0,n):
print ("%d"%( arr[i]),end=" ")
# Driver program
arr = [23, 10, 20, 11, 12, 6, 7]
1555
Chapter 235. Pancake sorting
n = len(arr)
pancakeSort(arr, n);
print ("Sorted Array ")
printArray(arr,n)
# This code is contributed by shreyanshi_arun.
C#
1556
Chapter 235. Pancake sorting
1557
Chapter 235. Pancake sorting
Output:
Sorted Array
6 7 10 11 12 20 23
Total O(n) flip operations are performed in above code. The overall time complexity is
O(n^2).
References:
http://en.wikipedia.org/wiki/Pancake_sorting
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/pancake-sorting/
1558
Chapter 236
Pandigital Product
Input : 7254
Output : Yes
39 * 186 = 7254. We can notice that
the three numbers 39, 186 and 7254
together have all digits from 1 to 9.
Input : 6952
Output : Yes
The idea is to consider all pairs that multiply to given number. For every pair, create a
string containing three numbers (given number and current pair). We sort the created string
and check if sorted string is equal to “123456789”.
C++
1559
Chapter 236. Pandigital Product
{
if (str.length() != 9)
return false;
char ch[str.length()];
strcpy(ch, str.c_str());
sort(ch, ch + str.length());
string s = ch;
if(s.compare("123456789") == 0)
return true;
else
return true;
}
// calculate the multiplicand,
// multiplier, and product
// eligible for pandigital
bool PandigitalProduct_1_9(int n)
{
for (int i = 1; i * i <= n; i++)
if (n % i == 0 && isPandigital(to_string(n) +
to_string(i) +
to_string(n / i)))
return true;
return false;
}
// Driver Code
int main()
{
int n = 6952;
if (PandigitalProduct_1_9(n) == true)
cout << "yes";
else
cout << "no";
return 0;
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Java
1560
Chapter 236. Pandigital Product
class GFG {
// calculate the multiplicand, multiplier, and product
// eligible for pandigital
public static boolean PandigitalProduct_1_9(int n)
{
for (int i = 1; i*i <= n; i++)
if (n % i == 0 && isPandigital("" + n + i + n / i))
return true;
return false;
}
// To check the string formed from multiplicand
// multiplier and product is pandigital
public static boolean isPandigital(String str)
{
if (str.length() != 9)
return false;
char ch[] = str.toCharArray();
Arrays.sort(ch);
return new String(ch).equals("123456789");
}
// Driver function
public static void main(String[] args)
{
int n = 6952;
if (PandigitalProduct_1_9(n) == true)
System.out.println("yes");
else
System.out.println("no");
}
}
C#
1561
Chapter 236. Pandigital Product
PHP
<?php
// PHP code to check the number
// is Pandigital Product or not
// To check the string formed
// from multiplicand, multiplier
// and product is pandigital
function isPandigital($str)
{
if (strlen($str) != 9)
return false;
$x = str_split($str);
1562
Chapter 236. Pandigital Product
sort($x);
$x = implode($x);
return strcmp($x, "123456789");
}
// calculate the multiplicand,
// multiplier, and product
// eligible for pandigital
function PandigitalProduct_1_9($n)
{
for ($i = 1;
$i * $i <= $n; $i++)
if ($n % $i == 0 &&
isPandigital(strval($n) .
strval($i) .
strval((int)($n / $i))))
return true;
return false;
}
// Driver Code
$n = 6050;
if (PandigitalProduct_1_9($n))
echo "yes";
else
echo "no";
// This code is contributed
// by mits
?>
Output:
yes
Source
https://www.geeksforgeeks.org/pandigital-product/
1563
Chapter 237
Permute two arrays such that sum of every pair is greater or equal to K - GeeksforGeeks
Given two arrays of equal size n and an integer k. The task is to permute both arrays such
that sum of their corresponding element is greater than or equal to k i.e a[i] + b[i] >= k.
The task is print “Yes” if any such permutation exists, otherwise print “No”.
Examples :
The idea is to sort one array in ascending order and another array in descending order and
if any index does not satisfy the condition a[i] + b[i] >= K then print “No”, else print “Yes”.
If the condition fails on sorted arrays, then there exists no permutation of arrays which can
satisfy the inequality. Proof,
Assume asort [] be sorted a[] in ascending order and bsort [] be sorted b[] in descending order.
Let new permutation b[] is created by swapping any two indices i, j of bsort [],
1564
Chapter 237. Permute two arrays such that sum of every pair is greater or equal to K
Java
1565
Chapter 237. Permute two arrays such that sum of every pair is greater or equal to K
Python3
1566
Chapter 237. Permute two arrays such that sum of every pair is greater or equal to K
# Check whether any
# permutation exists which
# satisfy the condition.
def isPossible(a,b,n,k):
# Sort the array a[]
# in decreasing order.
a.sort(reverse=True)
# Sort the array b[]
# in increasing order.
b.sort()
# Checking condition
# on each index.
for i in range(n):
if (a[i] + b[i] < k):
return False
return True
# Driver code
a = [ 2, 1, 3]
b = [7, 8, 9]
k = 10
n =len(a)
if(isPossible(a, b, n, k)):
print("Yes")
else:
print("No")
# This code is contributed
# by Anant Agarwal.
C#
1567
Chapter 237. Permute two arrays such that sum of every pair is greater or equal to K
PHP
<?php
// PHP program to check whether
// permutation of two arrays satisfy
// the condition a[i] + b[i] >= k.
// Check wheather any permutation
// exists which satisfy the condition.
function isPossible( $a, $b, $n, $k)
{
1568
Chapter 237. Permute two arrays such that sum of every pair is greater or equal to K
// Sort the array a[] in
// decreasing order.
sort($a);
// Sort the array b[] in
// increasing order.
rsort($b);
// Checking condition on each
// index.
for ( $i = 0; $i < $n; $i++)
if ($a[$i] + $b[$i] < $k)
return false;
return true;
}
// Driven Program
$a = array( 2, 1, 3 );
$b = array( 7, 8, 9 );
$k = 10;
$n = count($a);
if(isPossible($a, $b, $n, $k))
echo "Yes" ;
else
echo "No";
// This code is contributed by
// anuj_67.
?>
Output:
Yes
Source
https://www.geeksforgeeks.org/permute-two-arrays-sum-every-pair-greater-equal-k/
1569
Chapter 238
Pigeonhole Sort
1. Find minimum and maximum values in array. Let the minimum and maximum values
be ‘min’ and ‘max’ respectively. Also find range as ‘max-min-1’.
2. Set up an array of initially empty “pigeonholes” the same size as of the range.
3. Visit each element of the array and then put each element in its pigeonhole. An
element arr[i] is put in hole at index arr[i] – min.
4. Start the loop all over the pigeonhole array in order and put the elements from non-
empty holes back into the original array.
1570
Chapter 238. Pigeonhole Sort
C++
1571
Chapter 238. Pigeonhole Sort
Java
1572
Chapter 238. Pigeonhole Sort
Python3
1573
Chapter 238. Pigeonhole Sort
my_min = min(a)
my_max = max(a)
size = my_max - my_min + 1
# our list of pigeonholes
holes = [0] * size
# Populate the pigeonholes.
for x in a:
assert type(x) is int, "integers only please"
holes[x - my_min] += 1
# Put the elements back into the array in order.
i = 0
for count in range(size):
while holes[count] > 0:
holes[count] -= 1
a[i] = count + my_min
i += 1
a = [8, 3, 2, 7, 4, 6, 8]
print("Sorted order is : ", end = ' ')
pigeonhole_sort(a)
for i in range(0, len(a)):
print(a[i], end = ' ')
C#
// C# program to implement
// Pigeonhole Sort
using System;
class GFG
{
public static void pigeonhole_sort(int []arr,
int n)
{
int min = arr[0];
int max = arr[0];
int range, i, j, index;
for(int a = 0; a < n; a++)
{
if(arr[a] > max)
1574
Chapter 238. Pigeonhole Sort
max = arr[a];
if(arr[a] < min)
min = arr[a];
}
range = max - min + 1;
int[] phole = new int[range];
for(i = 0; i < n; i++)
phole[i] = 0;
for(i = 0; i < n; i++)
phole[arr[i] - min]++;
index = 0;
for(j = 0; j < range; j++)
while(phole[j] --> 0)
arr[index++] = j + min;
}
// Driver Code
static void Main()
{
int[] arr = {8, 3, 2, 7,
4, 6, 8};
Console.Write("Sorted order is : ");
pigeonhole_sort(arr,arr.Length);
for(int i = 0 ; i < arr.Length ; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed
// by Sam007
Output:
Sorted order is : 2 3 4 6 7 8 8
Pigeonhole sort has limited use as requirements are rarely met. For arrays where range is
1575
Chapter 238. Pigeonhole Sort
much larger than n, bucket sort is a generalization that is more efficient in space and time.
References:
https://en.wikipedia.org/wiki/Pigeonhole_sort
This article is contributed Ayush Govil. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/pigeonhole-sort/
1576
Chapter 239
One easy way to solve this problem is to use any stable sorting algorithm like Insertion Sort,
Merge Sort etc and then get the new index of given element but we can solve this problem
without sorting the array.
As position of an element in a sorted array is decided by only those elements which are
smaller than given element. We count all array elements smaller than given element and for
those elements which are equal to given element, elements occurring before given elements’
index will be included in count of smaller elements this will insure the stability of the result’s
index.
Simple code to implement above approach is implemented below:
C/C++
1577
Chapter 239. Position of an element after stable sort
// sorted array
#include <bits/stdc++.h>
using namespace std;
// Method returns the position of arr[idx] after
// performing stable-sort on array
int getIndexInSortedArray(int arr[], int n, int idx)
{
/* Count of elements smaller than current
element plus the equal element occurring
before given index*/
int result = 0;
for (int i = 0; i < n; i++) {
// If element is smaller then increase
// the smaller count
if (arr[i] < arr[idx])
result++;
// If element is equal then increase count
// only if it occurs before
if (arr[i] == arr[idx] && i < idx)
result++;
}
return result;
}
// Driver code to test above methods
int main()
{
int arr[] = { 3, 4, 3, 5, 2, 3, 4, 3, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int idxOfEle = 5;
cout << getIndexInSortedArray(arr, n, idxOfEle);
return 0;
}
Java
1578
Chapter 239. Position of an element after stable sort
Python
1579
Chapter 239. Position of an element after stable sort
for i in range(n):
# If element is smaller then increase
# the smaller count
if (arr[i] < arr[idx]):
result += 1
# If element is equal then increase count
# only if it occurs before
if (arr[i] == arr[idx] and i < idx):
result += 1
return result;
# Driver code to test above methods
arr = [3, 4, 3, 5, 2, 3, 4, 3, 1, 5]
n = len(arr)
idxOfEle = 5
print getIndexInSortedArray(arr, n, idxOfEle)
# Contributed by: Afzal Ansari
C#
1580
Chapter 239. Position of an element after stable sort
PHP
<?php
// PHP program to get index of
// array element in sorted array
// Method returns the position of
// arr[idx] after performing
// stable-sort on array
function getIndexInSortedArray( $arr, $n, $idx)
{
/* Count of elements smaller
than current element plus
the equal element occurring
before given index */
$result = 0;
for($i = 0; $i < $n; $i++)
{
// If element is smaller then
// increase the smaller count
if ($arr[$i] < $arr[$idx])
$result++;
// If element is equal then
// increase count only if
// it occurs before
1581
Chapter 239. Position of an element after stable sort
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/position-element-stable-sort/
1582
Chapter 240
Input : [4, 1, 2]
Output : No
No triangle is possible from given
array values
Input : [5, 4, 3, 1, 2]
Output : Yes
Sides of possible triangle are 2 3 4
A + B > C and
B + C > A and
C + A > B
where A, B and C are length of sides of the triangle.
The task is to find any triplet from array that satisfies above condition.
A Simple Solution is to generate all triplets and for every triplet check if it forms a triangle
or not by checking above three conditions.
1583
Chapter 240. Possible to form a triangle from array values
An Efficient Solution is use sorting. First, we sort the array then we loop once and we
will check three consecutive elements of this array if any triplet satisfies arr[i] + arr[i+1] >
arr[i+2], then we will output that triplet as our final result.
Why checking only 3 consecutive elements will work instead of trying all possible
triplets of sorted array?
Let we are at index i and 3 line segments are arr[i], arr[i + 1] and arr[i + 2] with relation
arr[i] < arr[i+1] < arr[i+2], If they can’t form a non-degenerate triangle, Line segments
of lengths arr[i-1], arr[i+1] and arr[i+2] or arr[i], arr[i+1] and arr[i+3] can’t form a non-
degenerate triangle also because sum of arr[i-1] and arr[i+1] will be even less than sum of
arr[i] and arr[i+1] in first case and sum of arr[i] and arr[i+1] must be less than arr[i+3] in
second case, So we don’t need to try all the combinations, we will try just 3 consecutive
indices of array in sorted form.
The total complexity of below solution is O(n log n)
C++
1584
Chapter 240. Possible to form a triangle from array values
int main()
{
int arr[] = {5, 4, 3, 1, 2};
int N = sizeof(arr) / sizeof(int);
isPossibleTriangle(arr, N) ? cout << "Yes" :
cout << "No";
return 0;
}
JAVA
1585
Chapter 240. Possible to form a triangle from array values
// Driver Code
static public void main (String[] args)
{
int []arr = {5, 4, 3, 1, 2};
int N = arr.length;
if(isPossibleTriangle(arr, N))
System.out.println("Yes" );
else
System.out.println("No");
}
}
// This code is contributed by vt_m.
Python
1586
Chapter 240. Possible to form a triangle from array values
C#
1587
Chapter 240. Possible to form a triangle from array values
if(isPossibleTriangle(arr, N))
Console.WriteLine("Yes" );
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find if
// it is possible to form
// a triangle from array values
// Method prints possible
// triangle when array values
// are taken as sides
function isPossibleTriangle( $arr, $N)
{
// If number of elements are
// less than 3, then no
// triangle is possible
if ($N < 3)
return false;
// first sort the array
sort($arr);
// loop for all 3
// consecutive triplets
for ( $i = 0; $i < $N - 2; $i++)
// If triplet satisfies triangle
// condition, break
if ($arr[$i] + $arr[$i + 1] > $arr[$i + 2])
return true;
}
// Driver Code
$arr = array(5, 4, 3, 1, 2);
$N = count($arr);
if(isPossibleTriangle($arr,$N))
echo "Yes" ;
else
1588
Chapter 240. Possible to form a triangle from array values
echo "No";
// This code is contributed by vt_m
?>
Output :
Yes
Improved By : vt_m
Source
https://www.geeksforgeeks.org/possible-form-triangle-array-values/
1589
Chapter 241
A Simple Solution is to use twp nested loops. The outer loop picks an element one by
one starting from the leftmost element. The inner loop checks if the element is present on
left side of it. If present, then ignores the element, else prints the element. Following is the
implementation of the simple algorithm.
C++
1590
Chapter 241. Print All Distinct Elements of a given integer array
Java
1591
Chapter 241. Print All Distinct Elements of a given integer array
if (i == j)
System.out.print( arr[i] + " ");
}
}
// Driver program
public static void main (String[] args)
{
int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
int n = arr.length;
printDistinct(arr, n);
}
}
// This code is contributed by vt_m
Python3
C#
1592
Chapter 241. Print All Distinct Elements of a given integer array
PHP
<?php
// PHP program to print all distinct
// elements in a given array
function printDistinct($arr, $n)
1593
Chapter 241. Print All Distinct Elements of a given integer array
{
// Pick all elements one by one
for($i = 0; $i < $n; $i++)
{
// Check if the picked element
// is already printed
$j;
for($j = 0; $j < $i; $j++)
if ($arr[$i] == $arr[$j])
break;
// If not printed
// earlier, then print it
if ($i == $j)
echo $arr[$i] , " ";
}
}
// Driver Code
$arr = array(6, 10, 5, 4, 9, 120, 4, 6, 10);
$n = sizeof($arr);
printDistinct($arr, $n);
// This code is contributed by nitin mittal
?>
Output:
6 10 5 4 9 120
Time Complexity of above solution is O(n2 ). We can Use Sorting to solve the problem
in O(nLogn) time. The idea is simple, first sort the array so that all occurrences of every
element become consecutive. Once the occurrences become consecutive, we can traverse the
sorted array and print distinct elements in O(n) time. Following is the implementation of
the idea.
C++
1594
Chapter 241. Print All Distinct Elements of a given integer array
// Traverse the sorted array
for (int i=0; i<n; i++)
{
// Move the index ahead while there are duplicates
while (i < n-1 && arr[i] == arr[i+1])
i++;
// print last occurrence of the current element
cout << arr[i] << " ";
}
}
// Driver program to test above function
int main()
{
int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
int n = sizeof(arr)/sizeof(arr[0]);
printDistinct(arr, n);
return 0;
}
Java
1595
Chapter 241. Print All Distinct Elements of a given integer array
}
}
// Driver program
public static void main (String[] args)
{
int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
int n = arr.length;
printDistinct(arr, n);
}
}
// This code is contributed by vt_m
C#
1596
Chapter 241. Print All Distinct Elements of a given integer array
PHP
<?php
// PHP program to print all distinct
// elements in a given array
function printDistinct( $arr, $n)
{
// First sort the array so
// that all occurrences
// become consecutive
sort($arr);
// Traverse the sorted array
for ($i = 0; $i < $n; $i++)
{
// Move the index ahead
// while there are duplicates
while ($i < $n - 1 and
$arr[$i] == $arr[$i + 1])
$i++;
// print last occurrence
// of the current element
echo $arr[$i] , " ";
}
}
// Driver Code
$arr = array(6, 10, 5, 4, 9, 120, 4, 6, 10);
$n = count($arr);
printDistinct($arr, $n);
// This code is contributed by anuj_67.
?>
Output:
1597
Chapter 241. Print All Distinct Elements of a given integer array
4 5 6 9 10 120
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the
given array from left to right and keep track of visited elements in a hash table. Following
is Java implementation of the idea.
Output:
10 5 3 4 6
One more advantage of hashing over sorting is, the elements are printed in same order as
they are in input array.
Improved By : Sam007, nitin mittal, vt_m
Source
https://www.geeksforgeeks.org/print-distinct-elements-given-integer-array/
1598
Chapter 242
Input : 7
/ \
6 5
/ \ / \
4 3 2 1
Output :
7
5 6
1 2 3 4
Input : 7
/ \
16 1
/ \
4 13
Output :
7
1 16
4 13
Here we can use two Priority queue for print in sorted order. We create an empty queue
q and two priority queues, current_level and next_level. We use NULL as a separator
between two levels. Whenever we encounter NULL in normal level order traversal, we swap
current_level and next_level.
1599
Chapter 242. Print Binary Tree levels in sorted order
1600
Chapter 242. Print Binary Tree levels in sorted order
1601
Chapter 242. Print Binary Tree levels in sorted order
Output:
Source
https://www.geeksforgeeks.org/print-binary-tree-levels-sorted-order/
1602
Chapter 243
Print Binary Tree levels in sorted order Set 2 (Using set) - GeeksforGeeks
Given a tree, print the level order traversal in sorted order.
Examples :
Input : 7
/ \
6 5
/ \ / \
4 3 2 1
Output :
7
5 6
1 2 3 4
Input : 7
/ \
16 1
/ \
4 13
Output :
7
1 16
4 13
1603
Chapter 243. Print Binary Tree levels in sorted order Set 2 (Using set)
In this post, a set (which is implemented using balanced binary search tree) based solution
is discussed.
Approach :
1. Start level order traversal of tree.
2. Store all the nodes in a set(or any other similar data structures).
3. Print elements of set.
C++
1604
Chapter 243. Print Binary Tree levels in sorted order Set 2 (Using set)
else {
s.insert(tmp->data);
if (tmp->left != nullptr)
q.push(tmp->left);
if (tmp->right != nullptr)
q.push(tmp->right);
}
}
}
// Driver code
int main()
{
Node* root = new Node(7);
root->left = new Node(6);
root->right = new Node(5);
root->left->left = new Node(4);
root->left->right = new Node(3);
root->right->left = new Node(2);
root->right->right = new Node(1);
sorted_level_order(root);
return 0;
}
Output:
7 5 6 1 2 3 4
Source
https://www.geeksforgeeks.org/print-binary-tree-levels-sorted-order-2/
1605
Chapter 244
Print all the pairs that contains the positive and negative values of an element - Geeks-
forGeeks
Given an array of distinct integers, print all the pairs having a positive value and negative
value of a number that exists in the array.
Note: Order of the pairs doesn’t matter.
Examples:
A naive approach is to run two loops i.e. Consider each element of the array using the
outer loop and search for its corresponding positive/negative value in the array using an
inner loop. Similarly, find all the pairs. Time Complexity of this approach will be O( n2 ).
A better approach is to use sorting i.e. first sort the array and then for each negative
element, do a binary search to find its counterpart (+ve number). If found, print that pair.
If the current element is positive then break that loop as after that there will be all the
positive numbers.
C++
1606
Chapter 244. Print all the pairs that contains the positive and negative values of an
element
Java
1607
Chapter 244. Print all the pairs that contains the positive and negative values of an
element
1608
Chapter 244. Print all the pairs that contains the positive and negative values of an
element
// by Arnab Kundu
Output:
-9, 9
-8, 8
-4, 4
-1, 1
C++
1609
Chapter 244. Print all the pairs that contains the positive and negative values of an
element
Output:
-4, 4
-1, 1
-8, 8
-9, 9
Source
https://www.geeksforgeeks.org/print-all-the-pairs-that-contains-the-positive-and-negative-values-of-an-element/
1610
Chapter 245
1611
Chapter 245. Print all triplets with given sum
Java
1612
Chapter 245. Print all triplets with given sum
Python 3
1613
Chapter 245. Print all triplets with given sum
C#
// A simple C# program
// to find three elements
// whose sum is equal to
// given sum
using System;
class GFG
{
// Prints all triplets in
// arr[] with given sum
static void findTriplets(int []arr,
int n, int sum)
{
for (int i = 0;
i < n - 2; i++)
{
for (int j = i + 1;
j < n - 1; j++)
{
for (int k = j + 1;
k < n; k++)
{
if (arr[i] + arr[j] + arr[k] == sum)
{
Console.WriteLine(arr[i]+ " "+
arr[j] +" "+
arr[k] );
}
}
}
}
}
// Driver code
static public void Main ()
{
int []arr = {0, -1, 2, -3, 1};
int n = arr.Length;
findTriplets(arr, n, -2);
}
}
// This code is contributed by akt_mit
PHP
1614
Chapter 245. Print all triplets with given sum
<?php
// A simple PHP program to
// find three elements whose
// sum is equal to given sum
// Prints all triplets in
// arr[] with given sum
function findTriplets($arr, $n, $sum)
{
for ($i = 0; $i < $n - 2; $i++)
{
for ($j = $i + 1; $j < $n - 1; $j++)
{
for ($k = $j + 1; $k < $n; $k++)
{
if ($arr[$i] + $arr[$j] +
$arr[$k] == $sum)
{
echo $arr[$i] , " ",
$arr[$j] , " ",
$arr[$k] , "\n";
}
}
}
}
}
// Driver code
$arr = array (0, -1, 2, -3, 1);
$n = sizeof($arr);
findTriplets($arr, $n, -2);
// This code is contributed by aj_36
?>
Output :
0 -3 1
-1 2 -3
1615
Chapter 245. Print all triplets with given sum
C++
Output:
-3 0 1
2 -1 -3
1616
Chapter 245. Print all triplets with given sum
C++
1617
Chapter 245. Print all triplets with given sum
l++;
// if sum is greater than given sum, then
// decrement in right side
else
r--;
}
}
}
// Driver code
int main()
{
int arr[] = { 0, -1, 2, -3, 1 };
int sum = -2;
int n = sizeof(arr) / sizeof(arr[0]);
findTriplets(arr, n, sum);
return 0;
}
Java
1618
Chapter 245. Print all triplets with given sum
C#
1619
Chapter 245. Print all triplets with given sum
// function to print
// triplets with given sum
static void findTriplets(int[] arr,
int n, int sum)
{
// sort array elements
Array.Sort(arr);
for (int i = 0; i < n - 1; i++)
{
// initialize left and right
int l = i + 1;
int r = n - 1;
int x = arr[i];
while (l < r)
{
if (x + arr[l] + arr[r] == sum)
{
// print elements if it's
// sum is given sum.
Console.WriteLine(x + " " + arr[l] +
" " + arr[r]);
l++;
r--;
}
// If sum of three elements
// is less than 'sum' then
// increment in left
else if (x + arr[l] +
arr[r] < sum)
l++;
// if sum is greater than
// given sum, then decrement
// in right side
else
r--;
}
}
}
// Driver code
static int Main()
{
int[] arr = new int[]{ 0, -1, 2, -3, 1 };
int sum = -2;
1620
Chapter 245. Print all triplets with given sum
int n = arr.Length;
findTriplets(arr, n, sum);
return 0;
}
}
// This code is contributed by rahul
PHP
<?php
// PHP program to find triplets
// in a given array whose sum
// is given sum.
// function to print triplets
// with given sum
function findTriplets($arr, $n, $sum)
{
// sort array elements
sort($arr);
for ($i = 0; $i < $n - 1; $i++)
{
// initialize left and right
$l = $i + 1;
$r = $n - 1;
$x = $arr[$i];
while ($l < $r)
{
if ($x + $arr[$l] +
$arr[$r] == $sum)
{
// print elements if it's
// sum is given sum.
echo $x, " ", $arr[$l],
" ", $arr[$r], "\n";
$l++;
$r--;
}
// If sum of three elements
// is less than 'sum' then
// increment in left
else if ($x + $arr[$l] +
$arr[$r] < $sum)
$l++;
1621
Chapter 245. Print all triplets with given sum
Output:
-3 -1 2
-3 0 1
Source
https://www.geeksforgeeks.org/print-all-triplets-with-given-sum/
1622
Chapter 246
Print array of strings in sorted order without copying one string into another - GeeksforGeeks
Given an array of n strings. The task is to print the strings in sorted order. The approach
should be such that no string should be copied to another string during sorting process.
Examples:
1. Maintain another array indexed_arr which stores/maintains the index of each string.
2. We can apply any sorting technique to this indexed_arr.
An Illustration:
1623
Chapter 246. Print array of strings in sorted order without copying one string into another
1624
Chapter 246. Print array of strings in sorted order without copying one string into another
Output:
Source
https://www.geeksforgeeks.org/print-array-strings-sorted-order-without-copying-one-string-another/
1625
Chapter 247
Print n smallest elements from given array in their original order - GeeksforGeeks
We are given an array of m-elements, we need to find n smallest elements from the array
but they must be in the same order as they are in given array.
Examples:
Make a copy of original array and then sort copy array. After sorting the copy array, save
all n smallest numbers. Further for each element in original array, check whether it is
in n-smallest number or not if it present in n-smallest array then print it otherwise move
forward.
1626
Chapter 247. Print n smallest elements from given array in their original order
Make copy_arr[]
sort(copy_arr)
For all elements in arr[] -
Output :
1 3 4 2 0
1627
Chapter 247. Print n smallest elements from given array in their original order
For making a copy of array we need space complexity of O(n) and then for sorting we will
need complexity of order O(n log n). Further for each element in arr[] we are performing
searching in copy_arr[], which will result O(n) for linear search but we can improve it by
applying binary search and hence our overall time complexity will be O(n log n).
Source
https://www.geeksforgeeks.org/find-n-smallest-element-given-array-order-array/
1628
Chapter 248
Print number in ascending order which contains 1, 2 and 3 in their digits. - GeeksforGeeks
Given an array of numbers, the task is to print those numbers in ascending order separated
by commas which have 1, 2 and 3 in their digits. If no number containing digits 1, 2, and 3
present then print -1.
Examples:
1629
Chapter 248. Print number in ascending order which contains 1, 2 and 3 in their digits.
// convert the number to string and find
// if it contains 1, 2 & 3.
bool findContainsOneTwoThree(int number)
{
string str = to_string(number);
int countOnes = 0, countTwo = 0, countThree = 0;
for(int i = 0; i < str.length(); i++) {
if(str[i] == '1') countOnes++;
else if(str[i] == '2') countTwo++;
else if(str[i] == '3') countThree++;
}
return (countOnes && countTwo && countThree);
}
// prints all the number containing 1, 2, 3
string printNumbers(int numbers[], int n)
{
vector<int> oneTwoThree;
for (int i = 0; i < n; i++)
{
// check if the number contains 1,
// 2 & 3 in any order
if (findContainsOneTwoThree(numbers[i]))
oneTwoThree.push_back(numbers[i]);
}
// sort all the numbers
sort(oneTwoThree.begin(), oneTwoThree.end());
string result = "";
for(auto number: oneTwoThree)
{
int value = number;
if (result.length() > 0)
result += ", ";
result += to_string(value);
}
return (result.length() > 0) ? result : "-1";
}
// Driver Code
int main() {
int numbers[] = { 123, 1232, 456, 234, 32145 };
1630
Chapter 248. Print number in ascending order which contains 1, 2 and 3 in their digits.
int n = sizeof(numbers)/sizeof(numbers[0]);
string result = printNumbers(numbers, n);
cout << result;
return 0;
}
// This code is contributed
// by Sirjan13
Java
1631
Chapter 248. Print number in ascending order which contains 1, 2 and 3 in their digits.
Python
1632
Chapter 248. Print number in ascending order which contains 1, 2 and 3 in their digits.
# Driver Code
numbers = [123, 1232, 456,
234, 32145]
result = printNumbers(numbers)
print ', '.join(num for num in result)
# This code is contributed
# by IshitaTripathi
Output:
Source
https://www.geeksforgeeks.org/print-number-ascending-order-contains-1-2-3-digits/
1633
Chapter 249
Input : 1, 3, 2, 2, 1
Output : 1 2 3
Input : 1, 1, 1, 2, 2, 3
Output : 1 2 3
Simple Solution is to sort the array first, then traverse the array and print only first
occurrences of elements.
Another Approach is to use set in C++ STL.
C++
1634
Chapter 249. Print sorted distinct elements of array
Java
C#
1635
Chapter 249. Print sorted distinct elements of array
// elements.
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static void printRepeating(int []arr, int size)
{
// Create a set using array elements
SortedSet<int> s = new SortedSet<int>(arr);
// Print contents of the set.
foreach (var n in s)
{
Console.Write(n + " ");
}
}
// Driver code
public static void Main()
{
int []arr = {1, 3, 2, 2, 1};
int n = arr.Length;
printRepeating(arr, n);
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Output:
1 2 3
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/print-sorted-distinct-elements-array-c/
1636
Chapter 250
A Simple Solution is to run three loops to consider all triplets one by one. For every
triplet, compare the sums and print current triplet if its sum is smaller than given sum.
C++
1637
Chapter 250. Print triplets with sum less than or equal to k
int printTriplets(int arr[], int n, int sum)
{
// Fix the first element as A[i]
for (int i = 0; i < n-2; i++)
{
// Fix the second element as A[j]
for (int j = i+1; j < n-1; j++)
{
// Now look for the third number
for (int k = j+1; k < n; k++)
if (arr[i] + arr[j] + arr[k] < sum)
cout << arr[i] << ", " << arr[j]
<< ", " << arr[k] << endl;
}
}
}
// Driver program
int main()
{
int arr[] = {5, 1, 3, 4, 7};
int n = sizeof arr / sizeof arr[0];
int sum = 12;
printTriplets(arr, n, sum);
return 0;
}
Java
1638
Chapter 250. Print triplets with sum less than or equal to k
Output:
5, 1, 3
5, 1, 4
1, 3, 4
1, 3, 7
1639
Chapter 250. Print triplets with sum less than or equal to k
of subarray
arr[i+1..n-1], i.e., j = i+1 and k = n-1
b) Move j and k toward each other until they meet,
i.e., while (j = sum), then do k--
1640
Chapter 250. Print triplets with sum less than or equal to k
}
}
}
// Driver program
int main()
{
int arr[] = { 5, 1, 3, 4, 7 };
int n = sizeof arr / sizeof arr[0];
int sum = 12;
printTriplets(arr, n, sum);
return 0;
}
Java
1641
Chapter 250. Print triplets with sum less than or equal to k
Output:
1, 3, 4
1, 3, 5
1, 3, 7
1, 4, 5
Source
https://www.geeksforgeeks.org/print-triplets-with-sum-less-than-or-equal-to-k/
1642
Chapter 251
Printing frequency of each character just after its consecutive occurrences - GeeksforGeeks
Given a string in such a way that every character occurs in a repeated manner. Your task
is to print the string by inserting the frequency of each unique character after it and also
eliminating all repeated characters.
Examples:
Input : GeeeEEKKKss
Output : G1e3E2K3s2
Input : ccccOddEEE
Output : c4o1d2E3
One approach to solve the above problem is to start a loop till the end of the string and
for every iteration, increment a count till the character at ith position matches the following
character.
Below is the implementation to the above given problem.
C++
1643
Chapter 251. Printing frequency of each character just after its consecutive occurrences
{
for (int i = 0; s[i] != '\0'; i++)
{
// Counting occurrences of s[i]
int count = 1;
while (s[i] == s[i + 1])
{
i++;
count++;
}
cout << s[i] << count << " ";
}
cout << endl;
}
// Driver code
int main()
{
printRLE("GeeeEEKKKss");
printRLE("ccccOddEEE");
return 0;
}
Java
1644
Chapter 251. Printing frequency of each character just after its consecutive occurrences
Python 3
1645
Chapter 251. Printing frequency of each character just after its consecutive occurrences
printRLE("GeeeEEKKKss")
printRLE("cccc0ddEEE")
# This code is contributed by ANKITRAI1
Output:
G1 e3 E2 K3 s2
c4 O1 d2 E3
Source
https://www.geeksforgeeks.org/printing-frequency-of-each-character-just-after-its-consecutive-occurrences/
1646
Chapter 252
The examples above show, we can have any data type elements present as an input and
output will be in a sorted form of the input data.
The idea here to solve this problem is to make a template.
Method 1 (Writing our own sort) In below code, we have implemented Bubble Sortto
sort the array.
1647
Chapter 252. Program for sorting variables of any data type
1648
Chapter 252. Program for sorting variables of any data type
float floatArr[n] = { 23.4, 11.4, -9.7, 11.17 };
sortArray(floatArr, n);
printArray(floatArr, n);
return 0;
}
Output:
1649
Chapter 252. Program for sorting variables of any data type
Output:
Source
https://www.geeksforgeeks.org/program-sorting-variables-data-type/
1650
Chapter 253
Input : 20 21 45 89 89 90
Output : Yes
Input : 20 20 45 89 89 90
Output : Yes
Input : 20 20 78 98 99 97
Output : No
Recursive approach:
The basic idea for recursive approach:
1651
Chapter 253. Program to check if an array is sorted or not (Iterative and Recursive)
Source
https://www.geeksforgeeks.org/program-check-array-sorted-not-iterative-recursive/
C++
Java
1652
Chapter 253. Program to check if an array is sorted or not (Iterative and Recursive)
class CkeckSorted
{
// Function that returns 0 if a pair
// is found unsorted
static int arraySortedOrNot(int arr[], int n)
{
// Array has one or no element or the
// rest are already checked and approved.
if (n == 1 || n == 0)
return 1;
// Unsorted pair found (Equal values allowed)
if (arr[n-1] < arr[n-2])
return 0;
// Last pair was sorted
// Keep on checking
return arraySortedOrNot(arr, n-1);
}
// main function
public static void main (String[] args)
{
int arr[] = {20, 23, 23, 45, 78, 88};
int n = arr.length;
if (arraySortedOrNot(arr, n)!=0)
System.out.println("Yes");
else
System.out.println("No");
}
}
Python3
1653
Chapter 253. Program to check if an array is sorted or not (Iterative and Recursive)
# Recursion applied till last element
return arr[0]<=arr[1] and arraySortedOrNot(arr[1:])
arr = [20, 23, 23, 45, 78, 88]
# Displaying result
if arraySortedOrNot(arr): print("Yes")
else: print("No")
Output:
Yes
1654
Chapter 253. Program to check if an array is sorted or not (Iterative and Recursive)
// Driver code
int main()
{
int arr[] = {20, 23, 23, 45, 78, 88};
int n = sizeof(arr)/sizeof(arr[0]);
if (arraySortedOrNot(arr, n))
cout << "Yes\n";
else
cout << "No\n";
}
Java
1655
Chapter 253. Program to check if an array is sorted or not (Iterative and Recursive)
}
}
// This code is contributed by Anant Agarwal.
Python3
Output:
Yes
1656
Chapter 254
• The minimum element out of the list of integers, must come in center position of array.
• The number in the ascending order next to the minimum, goes to the right, the next
higher number goes to the left of minimum number and it continues.
• As higher numbers are reached, one goes to one side in a to-and-fro manner similar to
that of a Pendulum.
Examples:
Input : 1 3 2 5 4
Output :5 3 1 2 4
Explanation:
The minimum element is 1, so it is moved to the middle.
The next higher element 2 is moved to the right of the
middle element while the next higher element 3 is
moved to the left of the middle element and
this process is continued.
Input : 11 12 31 14 5
Output :31 12 5 11 14
The idea is to sort the array first. Once the array is sorted, use an auxiliary array to store
elements one by one.
C++
1657
Chapter 254. Program to print an array in Pendulum Arrangement
1658
Chapter 254. Program to print an array in Pendulum Arrangement
// calling pendulum function
pendulumArrangement(arr, n);
return 0;
}
Java
1659
Chapter 254. Program to print an array in Pendulum Arrangement
System.out.println();
}
// Driver method
public static void main(String[] args)
{
//input Array
int arr[] = {14, 6, 19, 21, 12};
// calling pendulum function
pendulumArrangement(arr, arr.length);
}
}
Python3
1660
Chapter 254. Program to print an array in Pendulum Arrangement
C#
1661
Chapter 254. Program to print an array in Pendulum Arrangement
int j = 1, i = 1;
op[mid] = arr[0];
for (i = 1; i <= mid; i++)
{
op[mid + i] = arr[j++];
op[mid - i] = arr[j++];
}
// adjustment for when no.
// of elements is even
if (n % 2 == 0)
op[mid + i] = arr[j];
// Printing the pendulum arrangement
Console.Write("Pendulum arrangement:");
for (i = 0 ; i < n; i++)
Console.Write(op[i] + " ");
Console.WriteLine();
}
// Driver code
public static void Main()
{
//input Array
int []arr = {14, 6, 19, 21, 12};
// calling pendulum function
pendulumArrangement(arr, arr.Length);
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program for pendulum
// arrangement of numbers
// Prints pendulam arrangement of arr[]
function pendulumArrangement($arr, $n)
{
// sorting the elements
sort($arr, $n);
1662
Chapter 254. Program to print an array in Pendulum Arrangement
sort($arr);
// Auxiliary array to
// store output
$op[$n] = NULL;
// calculating the
// middle index
$mid = floor(($n - 1) / 2);
// storing the minimum
// element in the middle
// i is index for output
// array and j is for
// input array.
$j = 1;
$i = 1;
$op[$mid] = $arr[0];
for ($i = 1; $i <= $mid; $i++)
{
$op[$mid + $i] = $arr[$j++];
$op[$mid - $i] = $arr[$j++];
}
// adjustment for when no.
// of elements is even
if ($n % 2 == 0)
$op[$mid + $i] = $arr[$j];
// Printing the pendulum
// arrangement
echo "Pendulum arrangement:" ;
for ($i = 0 ; $i < $n; $i++)
echo $op[$i], " ";
echo "\n";
}
// Driver Code
//input Array
$arr = array(14, 6, 19, 21, 12);
// calculating the length
// of array A
$n = sizeof($arr);
// calling pendulum function
1663
Chapter 254. Program to print an array in Pendulum Arrangement
pendulumArrangement($arr, $n);
// This code is contributed by nitin mittal.
?>
Output:
Pendulum arrangement:
21 14 6 12 19
Source
https://www.geeksforgeeks.org/program-print-array-pendulum-arrangement/
1664
Chapter 255
Input : alkasingh
Output : snlkihgaa
Input : nupursingh
Output : uusrpnnihg
Input : geeksforgeeks
Output : ssrokkggfeeee
1665
Chapter 255. Program to sort string in descending order
int main()
{
string s = "geeksforgeeks";
descOrder(s); // function call
return 0;
}
Python
Output:
ssrokkggfeeee
1666
Chapter 255. Program to sort string in descending order
// in descending order
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
// function to print string in sorted order
void sortString(string& str)
{
// Hash array to keep count of characters.
// Initially count of all charters is
// initialized to zero.
int charCount[MAX_CHAR] = { 0 };
// Traverse string and increment
// count of characters
for (int i = 0; i < str.length(); i++)
// 'a'-'a' will be 0, 'b'-'a' will be 1,
// so for location of character in count
// array we wil do str[i]-'a'.
charCount[str[i] - 'a']++;
// Traverse the hash array and print
// characters
for (int i = MAX_CHAR - 1; i >= 0; i--)
for (int j = 0; j < charCount[i]; j++)
cout << (char)('a' + i);
}
// Driver program to test above function
int main()
{
string s = "alkasingh";
sortString(s);
return 0;
}
Output:
snlkihgaa
1667
Chapter 255. Program to sort string in descending order
Source
https://www.geeksforgeeks.org/program-sort-string-descending-order/
1668
Chapter 256
1669
Chapter 256. Python Code for time Complexity plot of Heap Sort
return 2 * i + 2
# calculate and return array size
def heapSize(A):
return len(A)-1
# This fuction takes an array and Heapyfies
# the at node i
def MaxHeapify(A, i):
# print("in heapy", i)
l = left(i)
r = right(i)
# heapSize = len(A)
# print("left", l, "Rightt", r, "Size", heapSize)
if l<= heapSize(A) and A[l] > A[i] :
largest = l
else:
largest = i
if r<= heapSize(A) and A[r] > A[largest]:
largest = r
if largest != i:
# print("Largest", largest)
A[i], A[largest]= A[largest], A[i]
# print("List", A)
MaxHeapify(A, largest)
# this function makes a heapified array
def BuildMaxHeap(A):
for i in range(int(heapSize(A)/2)-1, -1, -1):
MaxHeapify(A, i)
# Sorting is done using heap of array
def HeapSort(A):
BuildMaxHeap(A)
B = list()
heapSize1 = heapSize(A)
for i in range(heapSize(A), 0, -1):
A[0], A[i]= A[i], A[0]
B.append(A[heapSize1])
A = A[:-1]
heapSize1 = heapSize1-1
MaxHeapify(A, 0)
# randomly generates list of different
# sizes and call HeapSort funtion
1670
Chapter 256. Python Code for time Complexity plot of Heap Sort
elements = list()
times = list()
for i in range(1, 10):
# generate some integers
a = randint(0, 1000 * i, 1000 * i)
# print(i)
start = time.clock()
HeapSort(a)
end = time.clock()
# print("Sorted list is ", a)
print(len(a), "Elements Sorted by HeapSort in ", end-start)
elements.append(len(a))
times.append(end-start)
plt.xlabel('List Length')
plt.ylabel('Time Complexity')
plt.plot(elements, times, label ='Heap Sort')
plt.grid()
plt.legend()
plt.show()
# This code is contributed by Ashok Kajal
Output :
Source
https://www.geeksforgeeks.org/python-code-for-time-complexity-plot-of-heap-sort/
1671
Chapter 257
Source
https://www.geeksforgeeks.org/python-program-for-binary-insertion-sort/
Python
1672
Chapter 257. Python Program for Binary Insertion Sort
Please refer complete article on Binary Insertion Sort for more details!
1673
Chapter 258
Source
https://www.geeksforgeeks.org/python-program-for-bubble-sort/
Python
1674
Chapter 258. Python Program for Bubble Sort
1675
Chapter 259
• It is based on the idea that array to be sorted can be divided into cycles. Cycles can
be visualized as a graph. We have n nodes and an edge directed from node i to node
j if the element at i-th index must be present at j-th index in the sorted array.
Cycle in arr[] = {4, 5, 2, 1, 5}
1676
Chapter 259. Python Program for Cycle Sort
We one by one consider all cycles. We first consider the cycle that includes first element.
We find correct position of first element, place it at its correct position, say j. We consider
old value of arr[j] and find its correct position, we keep doing this till all elements of
current cycle are placed at correct position, i.e., we don\’t come back to cycle starting point.
Source
https://www.geeksforgeeks.org/python-program-for-cycle-sort/
Python3
1677
Chapter 259. Python Program for Cycle Sort
# Otherwise, put the item there or right after any duplicates.
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
writes += 1
# Rotate the rest of the cycle.
while pos != cycleStart:
# Find where to put the item.
pos = cycleStart
for i in range(cycleStart + 1, len(array)):
if array[i] < item:
pos += 1
# Put the item there or right after any duplicates.
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
writes += 1
return writes
# driver code
arr = [1, 8, 3, 9, 10, 10, 2, 4 ]
n = len(arr)
cycleSort(arr)
print("After sort : ")
for i in range(0, n) :
print(arr[i], end = \' \')
# Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:
After sort :
1 2 3 4 8 9 10 10
1678
Chapter 260
Source
https://www.geeksforgeeks.org/python-program-for-iterative-merge-sort/
Python
1679
Chapter 260. Python Program for Iterative Merge Sort
return result
def mergesort(list):
if len(list) < 2:
return list
middle = len(list)/2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(left, right)
seq = [12, 11, 13, 5, 6, 7]
print("Given array is")
print(seq);
print("\n")
print("Sorted array is")
print(mergesort(seq))
# Code Contributed by Mohit Gupta_OMG
Please refer complete article on Iterative Merge Sort for more details!
1680
Chapter 261
The key process in quickSort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x.
All this should be done in linear time.
Pseudo Code for recursive QuickSort function :
1681
Chapter 261. Python Program for QuickSort
Source
https://www.geeksforgeeks.org/python-program-for-quicksort/
Python
1682
Chapter 261. Python Program for QuickSort
1683
Chapter 262
Source
https://www.geeksforgeeks.org/python-program-for-recursive-insertion-sort/
Python
1684
Chapter 262. Python Program for Recursive Insertion Sort
insertionSortRecursive(arr,n-1)
\'\'\'Insert last element at its correct position
in sorted array.\'\'\'
last = arr[n-1]
j = n-2
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
while (j>=0 and arr[j]>last):
arr[j+1] = arr[j]
j = j-1
arr[j+1]=last
# A utility function to print an array of size n
def printArray(arr,n):
for i in range(n):
print arr[i],
# Driver program to test insertion sort
arr = [12,11,13,5,6]
n = len(arr)
insertionSortRecursive(arr, n)
printArray(arr, n)
# Contributed by Harsh Valecha
Please refer complete article on Recursive Insertion Sort for more details!
1685
Chapter 263
Source
https://www.geeksforgeeks.org/python-program-for-stooge-sort/
Python3
1686
Chapter 263. Python Program for Stooge Sort
arr[h] = t
# If there are more than 2 elements in
# the array
if h-l+1 > 2:
t = (int)((h-l+1)/3)
# Recursively sort first 2/3 elements
stoogesort(arr, l, (h-t))
# Recursively sort last 2/3 elements
stoogesort(arr, l+t, (h))
# Recursively sort first 2/3 elements
# again to confirm
stoogesort(arr, l, (h-t))
# deriver
arr = [2, 4, 5, 3, 1]
n = len(arr)
stoogesort(arr, 0, n-1)
for i in range(0, n):
print(arr[i], end = \' \')
# Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:
1 2 3 4 5
1687
Chapter 264
List_name.sort()
This will sort the given list in ascending order.
This function can be used to sort list of integers, floating point number, string and others.
numbers = [1, 3, 4, 2]
# Sorting list of Integers in ascending
numbers.sort()
print(numbers)
Output:
[1, 2, 3, 4]
list_name.sort(reverse=True)
This will sort the given list in descending order.
numbers = [1, 3, 4, 2]
# Sorting list of Integers in descending
numbers.sort(reverse = True)
print(numbers)
1688
Chapter 264. Python list sort()
Output:
[4, 3, 2, 1]
Output:
Source
https://www.geeksforgeeks.org/python-list-sort/
1689
Chapter 265
Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)]
m = 0
Output : [(1, 2), (2, 3), (2, 5), (4, 4)]
Explanation: Sorted using the 0th index key.
Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)]
m = 2
Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)]
Explanation: Sorted using the 2nd index key
Given tuples, we need to sort them according to any given key. This can be done using
sorted() function where we sort them using key=last and store last as the key index ac-
cording to which we have to sort the given tuples.
Below is the Python implementation of the above approach:
1690
Chapter 265. Python Sort Tuples in Increasing Order by any key
Output:
Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)]
Source
https://www.geeksforgeeks.org/python-sort-tuples-increasing-order-key/
1691
Chapter 266
There are many ways of performing this. Anyone can use there own algorithmic technique,
but Python provides us with various built-in functions to perform these. The built-in
functions include sort() and sorted() along with the key parameter. We can perform these
in two ways. One way is to sort the list by creating a new list and another way is to sort
within the given list, saving space.
The syntax for sorting by creating a new list is:
1692
Chapter 266. Python Sort a List according to the Length of the Elements
unsorted_list.sort(key=len)
Output:
Working:
These key function of Python’s while sorting implemented is known as the decorate-sort-
undecorate design pattern. It follows the following steps:
1. Each element of the list is temporarily replaced with a “decorated” version that in-
cludes the result of the key function applied to the element.
2. The list is sorted based upon the natural order of the keys.
3. The decorated elements are replaced by the original elements.
Reference: stackoverflow
Source
https://www.geeksforgeeks.org/python-sort-list-according-length-elements/
1693
Chapter 267
# Python code to sort the lists using the second element of sublists
# Inplace way to sort, use of third variable
def Sort(sub_li):
l = len(sub_li)
for i in range(0, l):
for j in range(0, l-i-1):
if (sub_li[j][1] > sub_li[j + 1][1]):
tempo = sub_li[j]
1694
Chapter 267. Python Sort a list according to the second element in sublist
sub_li[j]= sub_li[j + 1]
sub_li[j + 1]= tempo
return sub_li
# Driver Code
sub_li =[['rishav', 10], ['akash', 5], ['ram', 20], ['gaurav', 15]]
print(Sort(sub_li))
Output:
Output:
1. Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any
other iterator that needs to be sorted.
2. Key(optional) : A function that would server as a key or a basis of sort comparison.
1695
Chapter 267. Python Sort a list according to the second element in sublist
3. Reverse(optional) : To sort this in ascending order we could have just ignored the
third parameter, which we did in this program. If set true, then the iterable would be
sorted in reverse (descending) order, by default it is set as false.
Output:
Source
https://www.geeksforgeeks.org/python-sort-list-according-second-element-sublist/
1696
Chapter 268
Approach: Normally a dictionary in Python can hold only one value corresponding to a
key. But in this problem we may have to store multiple values for a particular key. Clearly,
simple dictionary cannot be used, we need something like a multimap in C++. So, here
1697
Chapter 268. Python Sort an array according to absolute difference
Default dictionary is use, which works as Multimap in Python. Following are the steps to
solve the problem.
• Store values in dictionary, where key is absolute difference between ‘val’ and array
elements (i.e. abs(val-a[i])) and value is array elements (i.e. a[i])
• In multiimap, the values will be already in sorted order according to key because it
implements self-balancing-bianry-search-tree internally.
• Update the values of original array by storing the dictionary elements one by one.
1698
Chapter 268. Python Sort an array according to absolute difference
Output:
7 4 8 2 12 0
Output:
7 4 8 2 12 0
1699
Chapter 268. Python Sort an array according to absolute difference
Source
https://www.geeksforgeeks.org/python-sort-an-array-according-to-absolute-difference/
1700
Chapter 269
We will use built in library function to sort the words of the sentence in ascending order.
Prerequisites:
1. split()
2. sort() in Python
3. join()
1701
Chapter 269. Python Sort words of sentence in ascending order
# Spliting the Sentence into words
words = Sentence.split(" ")
# Sorting the words
words.sort()
# Making new Sentence by
# joining the sorted words
newSentence = " ".join(words)
# Return newSentence
return newSentence
# Driver's Code
Sentence = "to learn programming refer geeksforgeeks"
# Print the sortedSentence
print(sortedSentence(Sentence))
Sentence = "geeks for geeks"
# Print the sortedSentence
print(sortedSentence(Sentence))
Output:
Source
https://www.geeksforgeeks.org/python-sort-words-sentence-ascending-order/
1702
Chapter 270
• The array of elements is divided into parts repeatedly until it is not possible to divide
it further.
• It is also known as “partition exchange sort”.
• It uses a key element (pivot) for partitioning the elements.
• One left partition contains all those elements that are smaller than the pivot and one
right partition contains all those elements which are greater than the key element.
1703
Chapter 270. Quick Sort vs Merge Sort
Merge sort is an external algorithm and based on divide and conquer strategy. In this:
• The elements are split into two sub-arrays (n/2) again and again until only one element
is left.
• Merge sort uses additional storage for sorting the auxiliary array.
• Merge sort uses three arrays where two are used for storing each half, and the third
external one is used to store the final sorted list by merging other two and each array
is then sorted recursively.
• At last, the all sub arrays are merged to make it ‘n’ element size of the array.
1704
Chapter 270. Quick Sort vs Merge Sort
1705
Chapter 270. Quick Sort vs Merge Sort
whereas
In merge sort, worst case and average case has same complexities O(n log n).
5. Efficiency :
Merge sort is more efficient and works faster than quick sort in case of larger array
size or datasets.
whereas
Quick sort is more efficient and works faster than merge sort in case of smaller array
size or datasets.
6. Sorting method :
The quick sort is internal sorting method where the data is sorted in main memory.
whereas
The merge sort is external sorting method in which the data that is to be sorted cannot
be accommodated in the memory and needed auxiliary memory for sorting.
7. Stability :
Merge sort is stable as two elements with equal value appear in the same order in
sorted output as they were in the input unsorted array.
whereas
Quick sort is unstable in this scenario. But it can be made stable using some changes
in code.
8. Preferred for :
Quick sort is preferred for arrays.
whereas
Merge sort is preferred for linked lists.
9. Locality of reference :
Quicksort exhibits good cache locality and this makes quicksort faster than merge sort
(in many cases like in virtual memory environment).
1706
Chapter 270. Quick Sort vs Merge Sort
[worst-case-complexity]
It works well on smaller It operates fine on any size
Works well on
array of array
[works-well-on]
It work faster than other It has a consistent speed
Speed of execution sorting algorithms for on any size of data
[speed-of-execution] small data set like
Selection sort etc
Less(In-place) More(not In-place)
Additional storage
space requirement
[additional-storage-space-
requirement]
Inefficient for larger arrays More efficient
Efficiency
[efficiency]
Internal External
Sorting method
[sorting-method]
Not Stable Stable
Stability
[stability]
for Arrays for Linked Lists
Preferred for
[preferred-for]
good poor
Locality of reference
[locality-of-reference]
Source
https://www.geeksforgeeks.org/quick-sort-vs-merge-sort/
1707
Chapter 271
QuickSort
QuickSort - GeeksforGeeks
Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot
and partitions the given array around the picked pivot. There are many different versions
of quickSort that pick pivot in different ways.
The key process in quickSort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x.
All this should be done in linear time.
Pseudo Code for recursive QuickSort function :
1708
Chapter 271. QuickSort
Partition Algorithm
There can be many ways to do partition, following pseudo code adopts the method given
in CLRS book. The logic is simple, we start from the leftmost element and keep track of
index of smaller (or equal to) elements as i. While traversing, if we find a smaller element,
we swap current element with arr[i]. Otherwise we ignore current element.
1709
Chapter 271. QuickSort
Illustration of partition() :
1710
Chapter 271. QuickSort
i = 2
arr[] = {10, 30, 40, 90, 80, 50, 70} // 80 and 40 Swapped
j = 5 : Since arr[j] <= pivot, do i++ and swap arr[i] with arr[j]
i = 3
arr[] = {10, 30, 40, 50, 80, 90, 70} // 90 and 50 Swapped
Implementation:
Following are C++, Java and Python implementations of QuickSort.
C/C++
/* C implementation QuickSort */
#include<stdio.h>
// A utility function to swap two elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
/* This function takes last element as pivot, places
the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot */
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
1711
Chapter 271. QuickSort
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}
Java
1712
Chapter 271. QuickSort
1713
Chapter 271. QuickSort
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = arr.length;
QuickSort ob = new QuickSort();
ob.sort(arr, 0, n-1);
System.out.println("sorted array");
printArray(arr);
}
}
/*This code is contributed by Rajat Mishra */
Python
1714
Chapter 271. QuickSort
C#
1715
Chapter 271. QuickSort
1716
Chapter 271. QuickSort
Output:
Sorted array:
1 5 7 8 9 10
Analysis of QuickSort
Time taken by QuickSort in general can be written as following.
The first two terms are for two recursive calls, the last term is for the partition process. k
is the number of elements which are smaller than pivot.
The time taken by QuickSort depends upon the input array and partition strategy. Following
are three cases.
Worst Case: The worst case occurs when the partition process always picks greatest or
smallest element as pivot. If we consider above partition strategy where last element is
always picked as pivot, the worst case would occur when the array is already sorted in
increasing or decreasing order. Following is recurrence for worst case.
1717
Chapter 271. QuickSort
The solution of above recurrence is (nLogn). It can be solved using case 2 of Master
Theorem.
Average Case:
To do average case analysis, we need to consider all possible permutation of array and
calculate time taken by every permutation which doesn’t look easy.
We can get an idea of average case by considering the case when partition puts O(n/9)
elements in one set and O(9n/10) elements in other set. Following is recurrence for this
case.
1718
Chapter 271. QuickSort
Snapshots:
1719
Chapter 271. QuickSort
1720
Chapter 271. QuickSort
• Quiz on QuickSort
1721
Chapter 271. QuickSort
References:
http://en.wikipedia.org/wiki/Quicksort
Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz:
Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Heap Sort, QuickSort, Radix Sort,
Counting Sort, Bucket Sort, ShellSort, Comb Sort, Pigeonhole Sort
Improved By : Palak Jain 5
Source
https://www.geeksforgeeks.org/quick-sort/
1722
Chapter 272
QuickSort Tail Call Optimization (Reducing worst case space to Log n ) - GeeksforGeeks
In QuickSort, partition function is in-place, but we need extra space for recursive function
calls. A simple implementation of QuickSort makes two calls to itself and in worst case
requires O(n) space on function call stack.
The worst case happens when the selected pivot always divides the array such that one part
has 0 elements and other part has n-1 elements. For example, in below code, if we choose
last element as pivot, we get worst case for sorted arrays (See this for visualization)
1723
Chapter 272. QuickSort Tail Call Optimization (Reducing worst case space to Log n )
Although we have reduced number of recursive calls, the above code can still use O(n)
auxiliary space in worst case. In worst case, it is possible that array is divided in a way that
the first part always has n-1 elements. For example, this may happen when last element is
choses as pivot and array is sorted in decreasing order.
We can optimize the above code to make a recursive call only for the smaller part after
partition. Below is implementation of this idea.
Further Optimization :
1724
Chapter 272. QuickSort Tail Call Optimization (Reducing worst case space to Log n )
{
quickSort(arr, low, pi - 1);
low = pi + 1;
}
// Else recur for right part
else
{
quickSort(arr, pi + 1, high);
high = pi - 1;
}
}
}
// See below link for complete running code
// https://ide.geeksforgeeks.org/LHxwPk
In the above code, if left part becomes smaller, then we make recursive call for left part.
Else for the right part. In worst case (for space), when both parts are of equal sizes in all
recursive calls, we use O(Log n) extra space.
Reference:
http://www.cs.nthu.edu.tw/~wkhon/algo08-tutorials/tutorial2b.pdf
This article is contributed by Dheeraj Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/quicksort-tail-call-optimization-reducing-worst-case-space-log-n/
1725
Chapter 273
1726
Chapter 273. QuickSort on Doubly Linked List
if (l < h)
{
int p = partition(A, l, h); /* Partitioning index */
quickSort(A, l, p - 1);
quickSort(A, p + 1, h);
}
}
C++
1727
Chapter 273. QuickSort on Doubly Linked List
{
while (root && root->next)
root = root->next;
return root;
}
/* Considers last element as pivot, places the pivot element at its
correct position in sorted array, and places all smaller (smaller than
pivot) to left of pivot and all greater elements to right of pivot */
Node* partition(Node *l, Node *h)
{
// set pivot as h element
int x = h->data;
// similar to i = l-1 for array implementation
Node *i = l->prev;
// Similar to "for (int j = l; j <= h- 1; j++)"
for (Node *j = l; j != h; j = j->next)
{
if (j->data <= x)
{
// Similar to i++ for array
i = (i == NULL)? l : i->next;
swap(&(i->data), &(j->data));
}
}
i = (i == NULL)? l : i->next; // Similar to i++
swap(&(i->data), &(h->data));
return i;
}
/* A recursive implementation of quicksort for linked list */
void _quickSort(struct Node* l, struct Node *h)
{
if (h != NULL && l != h && l != h->next)
{
struct Node *p = partition(l, h);
_quickSort(l, p->prev);
_quickSort(p->next, h);
}
}
// The main function to sort a linked list. It mainly calls _quickSort()
void quickSort(struct Node *head)
{
// Find last node
1728
Chapter 273. QuickSort on Doubly Linked List
1729
Chapter 273. QuickSort on Doubly Linked List
quickSort(a);
cout << "Linked List after sorting \n";
printList(a);
return 0;
}
Java
1730
Chapter 273. QuickSort on Doubly Linked List
1731
Chapter 273. QuickSort on Doubly Linked List
Output :
1732
Chapter 273. QuickSort on Doubly Linked List
Time Complexity: Time complexity of the above implementation is same as time com-
plexity of QuickSort() for arrays. It takes O(n^2) time in worst case and O(nLogn) in
average and best cases. The worst case occurs when the linked list is already sorted.
Can we implement random quick sort for linked list?
Quicksort can be implemented for Linked List only when we can pick a fixed point as
pivot (like last element in above implementation). Random QuickSort cannot be efficiently
implemented for Linked Lists by picking random pivot.
Exercise:
The above implementation is for doubly linked list. Modify it for singly linked list. Note
that we don’t have prev pointer in singly linked list.
Refer QuickSort on Singly Linked Listfor solution.
Source
https://www.geeksforgeeks.org/quicksort-for-linked-list/
1733
Chapter 274
1734
Chapter 274. QuickSort on Singly Linked List
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* A utility function to print linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
// Returns the last node of the list
struct Node *getTail(struct Node *cur)
{
while (cur != NULL && cur->next != NULL)
cur = cur->next;
return cur;
}
// Partitions the list taking the last element as the pivot
struct Node *partition(struct Node *head, struct Node *end,
struct Node **newHead, struct Node **newEnd)
{
struct Node *pivot = end;
struct Node *prev = NULL, *cur = head, *tail = pivot;
// During partition, both the head and end of the list might change
// which is updated in the newHead and newEnd variables
while (cur != pivot)
{
if (cur->data < pivot->data)
{
// First node that has a value less than the pivot - becomes
// the new head
if ((*newHead) == NULL)
(*newHead) = cur;
prev = cur;
cur = cur->next;
1735
Chapter 274. QuickSort on Singly Linked List
}
else // If cur node is greater than pivot
{
// Move cur node to next of tail, and change tail
if (prev)
prev->next = cur->next;
struct Node *tmp = cur->next;
cur->next = NULL;
tail->next = cur;
tail = cur;
cur = tmp;
}
}
// If the pivot data is the smallest element in the current list,
// pivot becomes the head
if ((*newHead) == NULL)
(*newHead) = pivot;
// Update newEnd to the current last node
(*newEnd) = tail;
// Return the pivot node
return pivot;
}
//here the sorting happens exclusive of the end node
struct Node *quickSortRecur(struct Node *head, struct Node *end)
{
// base condition
if (!head || head == end)
return head;
Node *newHead = NULL, *newEnd = NULL;
// Partition the list, newHead and newEnd will be updated
// by the partition function
struct Node *pivot = partition(head, end, &newHead, &newEnd);
// If pivot is the smallest element - no need to recur for
// the left part.
if (newHead != pivot)
{
// Set the node before the pivot node as NULL
struct Node *tmp = newHead;
while (tmp->next != pivot)
tmp = tmp->next;
1736
Chapter 274. QuickSort on Singly Linked List
tmp->next = NULL;
// Recur for the list before pivot
newHead = quickSortRecur(newHead, tmp);
// Change next of last node of the left half to pivot
tmp = getTail(newHead);
tmp->next = pivot;
}
// Recur for the list after the pivot element
pivot->next = quickSortRecur(pivot->next, newEnd);
return newHead;
}
// The main function for quick sort. This is a wrapper over recursive
// function quickSortRecur()
void quickSort(struct Node **headRef)
{
(*headRef) = quickSortRecur(*headRef, getTail(*headRef));
return;
}
// Driver program to test above functions
int main()
{
struct Node *a = NULL;
push(&a, 5);
push(&a, 20);
push(&a, 4);
push(&a, 3);
push(&a, 30);
cout << "Linked List before sorting \n";
printList(a);
quickSort(&a);
cout << "Linked List after sorting \n";
printList(a);
return 0;
}
Output:
1737
Chapter 274. QuickSort on Singly Linked List
30 3 4 20 5
Linked List after sorting
3 4 5 20 30
Source
https://www.geeksforgeeks.org/quicksort-on-singly-linked-list/
1738
Chapter 275
1739
Chapter 275. QuickSort using Random Pivoting
if i >= j then
return j
1740
Chapter 275. QuickSort using Random Pivoting
1741
Chapter 275. QuickSort using Random Pivoting
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition_r(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[] = { 10, 7, 8, 9, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Hoare (C++)
1742
Chapter 275. QuickSort using Random Pivoting
1743
Chapter 275. QuickSort using Random Pivoting
Output:
Sorted array: 1 5 7 8 9 10
Source
https://www.geeksforgeeks.org/quicksort-using-random-pivoting/
1744
Chapter 276
Quickselect Algorithm
The algorithm is similar to QuickSort. The difference is, instead of recurring for both sides
(after finding pivot), it recurs only for the part that contains the k-th smallest element. The
logic is simple, if index of partitioned element is more than k, then we recur for left part. If
index is same as k, we have found the k-th smallest element and we return. If index is less
than k, then we recur for right part. This reduces the expected complexity from O(n log n)
to O(n), with a worst case of O(n^2).
if left = right
return list[left]
1745
Chapter 276. Quickselect Algorithm
pivotIndex)
if k = pivotIndex
return list[k]
else if k < pivotIndex
right := pivotIndex - 1
else
left := pivotIndex + 1
1746
Chapter 276. Quickselect Algorithm
Output:
Important Points:
1. Like quicksort, it is fast in practice, but has poor worst-case performance. It is used
in
2. The partition process is same as QuickSort, only recursive code differs.
3. There exists an algorithm that finds k-th smallest element in O(n) in worst case, but
QuickSelect performs better on average.
Source
https://www.geeksforgeeks.org/quickselect-algorithm/
1747
Chapter 277
Radix Sort
1748
Chapter 277. Radix Sort
1749
Chapter 277. Radix Sort
1750
Chapter 277. Radix Sort
radixsort(arr, n);
print(arr, n);
return 0;
}
Java
1751
Chapter 277. Radix Sort
Python
1752
Chapter 277. Radix Sort
# The output array elements that will have sorted arr
output = [0] * (n)
# initialize count array as 0
count = [0] * (10)
# Store count of occurrences in count[]
for i in range(0, n):
index = (arr[i]/exp1)
count[ (index)%10 ] += 1
# Change count[i] so that count[i] now contains actual
# position of this digit in output array
for i in range(1,10):
count[i] += count[i-1]
# Build the output array
i = n-1
while i>=0:
index = (arr[i]/exp1)
output[ count[ (index)%10 ] - 1] = arr[i]
count[ (index)%10 ] -= 1
i -= 1
# Copying the output array to arr[],
# so that arr now contains sorted numbers
i = 0
for i in range(0,len(arr)):
arr[i] = output[i]
# Method to do Radix Sort
def radixSort(arr):
# Find the maximum number to know number of digits
max1 = max(arr)
# Do counting sort for every digit. Note that instead
# of passing digit number, exp is passed. exp is 10^i
# where i is current digit number
exp = 1
while max1/exp > 0:
countingSort(arr,exp)
exp *= 10
# Driver code to test above
arr = [ 170, 45, 75, 90, 802, 24, 2, 66]
radixSort(arr)
1753
Chapter 277. Radix Sort
for i in range(len(arr)):
print(arr[i]),
# This code is contributed by Mohit Kumra
Output:
2 24 45 66 75 90 170 802
Snapshots:
1754
Chapter 277. Radix Sort
1755
Chapter 277. Radix Sort
1756
Chapter 277. Radix Sort
1757
Chapter 277. Radix Sort
1758
Chapter 277. Radix Sort
1759
Chapter 277. Radix Sort
• Selection Sort
• Bubble Sort
• Insertion Sort
• Merge Sort
• Heap Sort
• QuickSort
• Counting Sort
• Bucket Sort
• ShellSort
References:
http://en.wikipedia.org/wiki/Radix_sort
http://alg12.wikischolars.columbia.edu/file/view/RADIX.pdf
MIT Video Lecture
Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E.
Leiserson, Ronald L. Rivest
Source
https://www.geeksforgeeks.org/radix-sort/
1760
Chapter 278
Input : 20 30 10
Output : 2.0 3.0 1.0
Input : 10 12 15 12 10 25 12
Output : 1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0
10 is the smallest and there are two 10s so
take the average of two consecutive ranks
1 and 2 i.e. 1.5 . Next smallest element is 12.
Since, two elements are already ranked, the
next rank that can be given is 3. However, there
are three 12's so the rank of 2 is (3+4+5) / 3 = 4.
Next smallest element is 15. There is only one 15
so 15 gets a rank of 6 since 5 elements are ranked.
Next element is 25 and it gets a rank of 7.
Input : 1, 2, 5, 2, 1, 60, 3
Output : 1.5, 3.5, 6.0, 3.5, 1.5, 7.0, 5.0
1761
Chapter 278. Rank of all elements in an array
there are exactly r elements which are less than e and s elements which are equal to e, then
e gets the rank given by
Algorithm
function rankify(A)
N = length of A
R is the array for storing ranks
for i in 0..N-1
r = 1, s = 1
for j in 0..N-1
if j != i and A[j] < A[i]
r += 1
if j != i and A[j] = A[i]
s += 1
// Assign Rank to A[i]
R[i] = r + 0.5*(s-1)
return R
1762
Chapter 278. Rank of all elements in an array
for (int j = 0; j < n; j++) {
if (j != i && A[j] < A[i])
r += 1;
if (j != i && A[j] == A[i])
s += 1;
}
// Use formula to obtain rank
R[i] = r + (float)(s - 1) / (float) 2;
}
for (int i = 0; i < n; i++)
cout << R[i] << ' ';
}
// Driver Code
int main() {
int A[] = {1, 2, 5, 2, 1, 25, 2};
int n = sizeof(A) / sizeof(A[0]);
for (int i = 0; i < n; i++)
cout << A[i] << ' ';
cout << '\n';
rankify(A, n);
return 0;
}
// This code is contributed by Gitanjali.
Java
1763
Chapter 278. Rank of all elements in an array
Python3
1764
Chapter 278. Rank of all elements in an array
C#
1765
Chapter 278. Rank of all elements in an array
Output
[1, 2, 5, 2, 1, 25, 2]
[1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0]
Time Complexity is O(N*N), while space complexity is O(1) (excluding space required to
hold ranks)
Method II (Efficient)
In this method, create another array (T) of tuples. The first element of the tuple stores the
value while the second element refers to the index of the value in the array. Then, sort T in
ascending order using the first value of each tuple. Once sorted it is guaranteed that equal
elements become adjacent. Then simply walk down T, find the no of adjacent elements and
set ranks for each of these elements. Use the second member of each tuple to determine the
indices of the values.
1766
Chapter 278. Rank of all elements in an array
Algorithm
function rankify_improved(A)
N = Length of A
T = Array of tuples (i,j),
where i = A[i] and j = i
R = Array for storing ranks
Sort T in ascending order
according to i
for j in 0...N-1
k = j
// No of adjacent elements
n = k - j + 1
// Skip n ranks
r += n
// Skip n indices
j += n
return R
1767
Chapter 278. Rank of all elements in an array
# Create an auxiliary array of tuples
# Each tuple stores the data as well
# as its index in A
T = [(A[i], i) for i in range(len(A))]
# T[][0] is the data and T[][1] is
# the index of data in A
# Sort T according to first element
T.sort(key=lambda x: x[0])
(rank, n, i) = (1, 1, 0)
while i < len(A):
j = i
# Get no of elements with equal rank
while j < len(A) - 1 and T[j][0] == T[j + 1][0]:
j += 1
n = j - i + 1
for j in range(n):
# For each equal element use formula
# obtain index of T[i+j][0] in A
idx = T[i+j][1]
R[idx] = rank + (n - 1) * 0.5
# Increment rank and i
rank += n
i += n
return R
if __name__ == "__main__":
A = [1, 2, 5, 2, 1, 25, 2]
print(A)
print(rankify_improved(A))
Output
[1, 2, 5, 2, 1, 25, 2]
[1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0]
Time Complexity depends on the sorting procedure which is typically O(N Log N). The
auxiliary space is O(N), since we need to store the indices as well as values.
1768
Chapter 278. Rank of all elements in an array
Source
https://www.geeksforgeeks.org/rank-elements-array/
1769
Chapter 279
Rearrange an array in
maximum minimum form Set 1
1770
Chapter 279. Rearrange an array in maximum minimum form Set 1
1771
Chapter 279. Rearrange an array in maximum minimum form Set 1
Java
1772
Chapter 279. Rearrange an array in maximum minimum form Set 1
System.out.println(Arrays.toString(arr));
rearrange(arr,arr.length);
System.out.println("Modified Array ");
System.out.println(Arrays.toString(arr));
}
}
Python
1773
Chapter 279. Rearrange an array in maximum minimum form Set 1
n = len(arr)
print("Original Array")
print(arr)
print("Modified Array")
print(rearrange(arr, n))
# This code is contributed by Pratik Chhajer
C#
// C# program to rearrange
// an array in minimum
// maximum form
using System;
class GFG
{
// Prints max at first position,
// min at second position second
// max at third position, second
// min at fourth position and so on.
static void rearrage(int[] arr,
int n)
{
// Auxiliary array to
// hold modified array
int []temp = new int[n];
// Indexes of smallest
// and largest elements
// from remaining array.
int small = 0, large = n - 1;
// To indicate whether we
// need to copy rmaining
// largest or remaining
// smallest at next position
bool flag = true;
// Store result in temp[]
for (int i = 0; i < n; i++)
{
if (flag)
temp[i] = arr[large--];
else
temp[i] = arr[small++];
1774
Chapter 279. Rearrange an array in maximum minimum form Set 1
flag = !flag;
}
// Copy temp[] to arr[]
for (int i = 0; i < n; i++)
arr[i] = temp[i];
}
// Driver Code
static void Main()
{
int[] arr = {1, 2, 3, 4,
5, 6, 7, 8, 9};
Console.WriteLine("Original Array");
for(int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
rearrage(arr, arr.Length);
Console.WriteLine("\nModified Array");
for(int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed
// by Sam007
Output:
Original Array
1 2 3 4 5 6 7 8 9
Modified Array
9 1 8 2 7 3 6 4 5
1775
Chapter 279. Rearrange an array in maximum minimum form Set 1
Source
https://www.geeksforgeeks.org/rearrange-array-maximum-minimum-form/
1776
Chapter 280
Rearrange an array in
maximum minimum form Set 2
(O(1) extra space)
Rearrange an array in maximum minimum form Set 2 (O(1) extra space) - GeeksforGeeks
Given a sorted array of positive integers, rearrange the array alternately i.e first element
should be the maximum value, second minimum value, third-second max, fourth-second min
and so on.
Examples:
1777
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
For i = 0 to n-1
If 'i' is even
arr[i] += arr[max_index] % max_element * max_element
max_index--
ELSE // if 'i' is odd
arr[i] += arr[min_index] % max_element * max_element
min_index++
1778
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
}
// at odd index : we have to put minimum element
else {
arr[i] += (arr[min_idx] % max_elem) * max_elem;
min_idx++;
}
}
// array elements back to it's original form
for (int i = 0; i < n; i++)
arr[i] = arr[i] / max_elem;
}
// Driver program to test above function
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original Arrayn";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
rearrange(arr, n);
cout << "\nModified Array\n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Java
1779
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
Python3
1780
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
# Prints max at first position, min at second position
# second max at third position, second min at fourth
# position and so on.
def rearrange(arr, n):
# Initialize index of first minimum
# and first maximum element
max_idx = n - 1
min_idx = 0
# Store maximum element of array
max_elem = arr[n-1] + 1
# Traverse array elements
for i in range(0, n) :
# At even index : we have to put maximum element
if i % 2 == 0 :
arr[i] += (arr[max_idx] % max_elem ) * max_elem
max_idx -= 1
# At odd index : we have to put minimum element
else :
arr[i] += (arr[min_idx] % max_elem ) * max_elem
min_idx += 1
# array elements back to it's original form
for i in range(0, n) :
arr[i] = arr[i] / max_elem
# Driver Code
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
print ("Original Array")
for i in range(0, n):
print (arr[i], end = " ")
rearrange(arr, n)
print ("\nModified Array")
for i in range(0, n):
print (int(arr[i]), end = " ")
# This code is contributed by Shreyanshi Arun.
1781
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
C#
// C# program to rearrange an
// array in minimum maximum form
using System;
class main {
// Prints max at first position, min at second
// position, second max at third position, second
// min at fourth position and so on.
public static void rearrange(int[] arr, int n)
{
// initialize index of first minimum
// and first maximum element
int max_idx = n - 1, min_idx = 0;
// store maximum element of array
int max_elem = arr[n - 1] + 1;
// traverse array elements
for (int i = 0; i < n; i++) {
// at even index : we have to put
// maximum element
if (i % 2 == 0) {
arr[i] += (arr[max_idx] % max_elem) * max_elem;
max_idx--;
}
// at odd index : we have to
// put minimum element
else {
arr[i] += (arr[min_idx] % max_elem) * max_elem;
min_idx++;
}
}
// array elements back to it's original form
for (int i = 0; i < n; i++)
arr[i] = arr[i] / max_elem;
}
// Driver code
public static void Main()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = arr.Length;
1782
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
Console.WriteLine("Original Array");
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
rearrange(arr, n);
Console.WriteLine("Modified Array");
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by vt_m.
Output :
Original Array
1 2 3 4 5 6 7 8 9
Modified Array
9 1 8 2 7 3 6 4 5
Thanks Saurabh Srivastava and Gaurav Ahirwar for suggesting this approach.
Another Approach: A simpler approach will be to observe indexing positioning of maxi-
mum elements and minimum elements. The even index stores maximum elements and the
odd index stores the minimum elements. With every increasing index, the maximum ele-
ment decreases by one and the minimum element increases by one. A simple traversal can
be done and arr[] can be filled in again.
Below is the implementation of the above approach:
C++
1783
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
Java
1784
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
C#
// C# program to rearrange
// an array in minimum
// maximum form
using System;
class GFG
{
// Prints max at first
// position, min at second
// position second max at
// third position, second
1785
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
1786
Chapter 280. Rearrange an array in maximum minimum form Set 2 (O(1) extra space)
}
}
// This code is contributed by ajit
Output :
Original Array
1 2 3 4 5 6 7 8 9
Modified Array
9 1 8 2 7 3 6 4 5
Source
https://www.geeksforgeeks.org/rearrange-array-maximum-minimum-form-set-2-o1-extra-space/
1787
Chapter 281
Rearrange an array in order - smallest, largest, 2nd smallest, 2nd largest, .. - GeeksforGeeks
Given an array of integers, task is to print the array in the order – smallest number, Largest
number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number
and so on…..
Examples:
A simple solution is to first find the smallest element, swap it with first element. Then find
largest element, swap it with second element and so on. Time complexity of this solution is
O(n2 ).
An efficient solution is to use sorting.
1. Sort the elements of array.
2. Take two variables say i and j and point them to the first and last index of the array
respectively.
3. Now run a loop and store the elements in the array one by one by incrementing i and
decrementing j.
Let’s take an array with input 5, 8, 1, 4, 2, 9, 3, 7, 6 and sort them so the array become 1,
2, 3, 4, 5, 6, 7, 8, 9. Now take two variables say i and j and point them to the first and last
1788
Chapter 281. Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
index of the array respectively, run a loop and store value into new array by incrementing i
and decrementing j. We get final result as 1 9 2 8 3 7 4 6 5.
C++
Java
1789
Chapter 281. Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
1790
Chapter 281. Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
}
// This code is contributed by Sumit Ghosh
Python3
1791
Chapter 281. Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
# This code is contributed by Nikita Tiwari.
C#
1792
Chapter 281. Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
{
int []arr = {5, 8, 1, 4, 2, 9, 3, 7, 6};
int n = arr.Length;
rearrangeArray(arr, n);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program to print
// the array in given order
// Function which
// arrange the array.
function rearrangeArray($arr, $n)
{
// Sorting the
// array elements
sort($arr);
// To store modified array
$tempArr = array($n);
// Adding numbers from
// sorted array to new
// array accordingly
$ArrIndex = 0;
// Traverse from begin
// and end simultaneously
for ($i = 0, $j = $n - 1;
$i <= $n / 2 || $j > $n / 2;
$i++, $j--)
{
$tempArr[$ArrIndex] = $arr[$i];
$ArrIndex++;
$tempArr[$ArrIndex] = $arr[$j];
$ArrIndex++;
}
// Modifying original array
for ($i = 0; $i < $n; $i++)
1793
Chapter 281. Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
$arr[$i] = $tempArr[$i];
for ($i = 0; $i < $n; $i++)
echo $arr[$i] . " ";
}
// Driver Code
$arr = array(5, 8, 1, 4, 2,
9, 3, 7, 6 );
$n = count($arr) ;
rearrangeArray($arr, $n);
// This code is contributed
// by Sam007
?>
Output:
1 9 2 8 3 7 4 6 5
Source
https://www.geeksforgeeks.org/rearrange-array-order-smallest-largest-2nd-smallest-2nd-largest/
1794
Chapter 282
This problem is a variation of Minimize the sum of product of two arrays with permutations
allowed.
1795
Chapter 282. Rearrange an array to minimize sum of product of consecutive pair elements
For rearranging the array in such a way that we should get the sum of the product of
consecutive element pairs is minimum we should have all even index element in decreasing
and odd index element in increasing order with all n/2 maximum elements as even indexed
and next n/2 elements as odd indexed or vice-versa.
Now, for that our idea is simple, we should sort the main array and further create two
auxiliary arrays evenArr[] and oddArr[] respectively. We traverse input array and put n/2
maximum elements in evenArr[] and next n/2 elements in oddArr[]. Then we sort evenArr[]
in descending and oddArr[] in ascending order. Finally, copy evenArr[] and oddArr[] element
by element to get the required result and should calculate the minimum required sum.
1796
Chapter 282. Rearrange an array to minimize sum of product of consecutive pair elements
return sum;
}
// Driver Program
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Minimum required sum = " << minSum(arr, n);
cout << "\nSorted array in required format : ";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/rearrange-array-minimize-sum-product-consecutive-pair-elements/
1797
Chapter 283
Rearrange array such that even positioned are greater than odd - GeeksforGeeks
Given an array A of n elements, sort the array according to the following relations :
, if i is even.
, if i is odd.
Print the resultant array.
Examples :
Observe that array consists of [n/2] even positioned elements. If we assign largest [n/2]
elements to the even positions and rest of the elements to the odd positions, our problem
is solved. Because element at odd position will always be less than the element at even
position as it is maximum element and vice versa. Sort the array and assign the first [n/2]
elements at even positions.
1798
Chapter 283. Rearrange array such that even positioned are greater than odd
Java
1799
Chapter 283. Rearrange array such that even positioned are greater than odd
import java.util.*;
class GFG {
static void assign(int a[], int n) {
// Sort the array
Arrays.sort(a);
int ans[] = new int[n];
int p = 0, q = n - 1;
for (int i = 0; i < n; i++) {
// Assign even indexes with maximum elements
if ((i + 1) % 2 == 0)
ans[i] = a[q--];
// Assign odd indexes with remaining elements
else
ans[i] = a[p++];
}
// Print result
for (int i = 0; i < n; i++)
System.out.print(ans[i] + " ");
}
// Driver code
public static void main(String args[]) {
int A[] = {1, 3, 2, 2, 5};
int n = A.length;
assign(A, n);
}
}
// This code is contributed by Nikita Tiwari.
Python3
1800
Chapter 283. Rearrange array such that even positioned are greater than odd
ans = [0] * n
p = 0
q = n - 1
for i in range(n):
# Assign even indexes with
# maximum elements
if (i + 1) % 2 == 0:
ans[i] = a[q]
q = q - 1
# Assign odd indexes with
# remaining elements
else:
ans[i] = a[p]
p = p + 1
# Print result
for i in range(n):
print(ans[i], end = " ")
# Driver Code
A = [ 1, 3, 2, 2, 5 ]
n = len(A)
assign(A, n)
# This code is contributed by "Sharad_Bhardwaj".
C#
1801
Chapter 283. Rearrange array such that even positioned are greater than odd
if ((i + 1) % 2 == 0)
ans[i] = a[q--];
// Assign odd indexes with remaining elements
else
ans[i] = a[p++];
}
// Print result
for (int i = 0; i < n; i++)
Console.Write(ans[i] + " ");
}
// Driver code
public static void Main()
{
int[] A = { 1, 3, 2, 2, 5 };
int n = A.Length;
assign(A, n);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to rearrange
// the elements in array such
// that even positioned are
// greater than odd positioned
// elements
function assign($a, $n)
{
// Sort the array
sort($a);
$p = 0; $q = $n - 1;
for ($i = 0; $i < $n; $i++)
{
// Assign even indexes
// with maximum elements
if (($i + 1) % 2 == 0)
$ans[$i] = $a[$q--];
1802
Chapter 283. Rearrange array such that even positioned are greater than odd
Output:
1 5 2 3 2
Improved By : jit_t
Source
https://www.geeksforgeeks.org/rearrange-array-such-that-even-positioned-are-greater-than-odd/
1803
Chapter 284
Rearrange positive and negative numbers using inbuilt sort function - GeeksforGeeks
Given an array of positive and negative numbers, arrange them such that all negative
integers appear before all the positive integers in the array without using any additional
data structure like hash table, arrays, etc. The order of appearance should be maintained.
Examples:
Previous Approaches : Some of the approaches have already been discussed here. They were
implemented at best.
Another Approach : There is another method to do so. In c++ STL, There is an inbuilt
function std::sort(). We can modify the comp() function to obtain the desired result. As
we have to place negative numbers first and then positive numbers. We also have to keep
zero’s(if present) between positive and negative numbers.
The comp() function in this code rearranges the given array in required order. Here in bool
comp(int a, int b), if integer ‘a’ is of j-th index and integer ‘b’ is of i-th index elements in
the arr[], then j>i. comp() function will be called in this way. If the comp() return true
then swap will be done.
1804
Chapter 284. Rearrange positive and negative numbers using inbuilt sort function
Output:
-12 -13 -5 -7 -3 -6 11 6 5
1805
Chapter 284. Rearrange positive and negative numbers using inbuilt sort function
Time complexity is same as sorting i.e. O(n log n). As we are using standard sort
function. But it is really faster, because inbuilt sort function uses introsort.
Improved By : Siva Saindra Reddy K
Source
https://www.geeksforgeeks.org/rearrange-positive-negative-numbers-using-inbuilt-sort-function/
1806
Chapter 285
Rearrange positive and negative numbers with constant extra space - GeeksforGeeks
Given an array of positive and negative numbers, arrange them such that all negative integers
appear before all the positive integers in the array without using any additional data
structure like hash table, arrays, etc. The order of appearance should be maintained.
Examples:
A simple solution is to use another array. We copy all elements of original array to new
array. We then traverse the new array and copy all negative and positive elements back in
original array one by one. This approach is discussed here. The problem with this approach
is that it uses auxiliary array and we’re not allowed to use any data structure to solve this
problem.
One approach that does not use any data structure is to use use partition process of Quick-
Sort. The idea is to consider 0 as pivot and divide the array around it. The problem with
this approach is that it changes relative order of elements. The similar partition process is
discussed here.
Let’s now discuss few methods which do not use any other data structure and also preserves
relative order of elements.
Approach 1: Modified Insertion Sort
We can modify insertion sort to solve this problem.
Algorithm –
1807
Chapter 285. Rearrange positive and negative numbers with constant extra space
Loop from i = 1 to n - 1.
a) If the current element is positive, do nothing.
b) If the current element arr[i] is negative, we
insert it into sequence arr[0..i-1] such that
all positive elements in arr[0..i-1] are shifted
one position to their right and arr[i] is inserted
at index of first positive element.
1808
Chapter 285. Rearrange positive and negative numbers with constant extra space
Java
1809
Chapter 285. Rearrange positive and negative numbers with constant extra space
C#
1810
Chapter 285. Rearrange positive and negative numbers with constant extra space
{
int key, j;
for (int i = 1; i < n; i++) {
key = arr[i];
// if current element is positive
// do nothing
if (key > 0)
continue;
/* if current element is negative,
shift positive elements of arr[0..i-1],
to one position to their right */
j = i - 1;
while (j >= 0 && arr[j] > 0) {
arr[j + 1] = arr[j];
j = j - 1;
}
// Put negative element at its right position
arr[j + 1] = key;
}
}
// Driver program
public static void Main()
{
int[] arr = { -12, 11, -13, -5, 6,
-7, 5, -3, -6 };
int n = arr.Length;
RearrangePosNeg(arr, n);
printArray(arr, n);
}
}
// This code is contributed by vt_m.
Output:
-12 -13 -5 -7 -3 -6 11 6 5
Time complexity of above solution is O(n2 ) and auxiliary space is O(1). We have maintained
the order of appearance and have not used any other data structure.
Approach 2: Optimized Merge Sort
Merge method of standard merge sort algorithm can be modified to solve this problem.
While merging two sorted halves say left and right, we need to merge in such a way that
1811
Chapter 285. Rearrange positive and negative numbers with constant extra space
negative part of left and right sub-array is copied first followed by positive part of left and
right sub-array.
Below is the implementation of the idea –
C++
1812
Chapter 285. Rearrange positive and negative numbers with constant extra space
// copy negative elements of right subarray
while (j < n2 && R[j] < 0)
arr[k++] = R[j++];
// copy positive elements of left subarray
while (i < n1)
arr[k++] = L[i++];
// copy positive elements of right subarray
while (j < n2)
arr[k++] = R[j++];
}
// Function to Rearrange positive and negative
// numbers in a array
void RearrangePosNeg(int arr[], int l, int r)
{
if(l < r)
{
// Same as (l + r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
RearrangePosNeg(arr, l, m);
RearrangePosNeg(arr, m + 1, r);
merge(arr, l, m, r);
}
}
/* Driver program to test above functions */
int main()
{
int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
RearrangePosNeg(arr, 0, arr_size - 1);
printArray(arr, arr_size);
return 0;
}
Java
1813
Chapter 285. Rearrange positive and negative numbers with constant extra space
1814
Chapter 285. Rearrange positive and negative numbers with constant extra space
arr[k++] = L[i++];
// copy negative elements of right subarray
while (j < n2 && R[j] < 0)
arr[k++] = R[j++];
// copy positive elements of left subarray
while (i < n1)
arr[k++] = L[i++];
// copy positive elements of right subarray
while (j < n2)
arr[k++] = R[j++];
}
// Function to Rearrange positive and negative
// numbers in a array
static void RearrangePosNeg(int arr[], int l, int r)
{
if(l < r)
{
// Same as (l + r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
RearrangePosNeg(arr, l, m);
RearrangePosNeg(arr, m + 1, r);
merge(arr, l, m, r);
}
}
// Driver program
public static void main (String[] args)
{
int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
int arr_size = arr.length;
RearrangePosNeg(arr, 0, arr_size - 1);
printArray(arr, arr_size);
}
}
// This code is contributed by vt_m.
C#
1815
Chapter 285. Rearrange positive and negative numbers with constant extra space
1816
Chapter 285. Rearrange positive and negative numbers with constant extra space
Output:
1817
Chapter 285. Rearrange positive and negative numbers with constant extra space
-12 -13 -5 -7 -3 -6 11 6 5
Time complexity of above solution is O(n log n). The problem with this approach is we are
using auxiliary array for merging but we’re not allowed to use any data structure to solve
this problem. We can do merging in-place without using any data-structure. The idea is
taken from here.
Let Ln and Lp denotes the negative part and positive part of left sub-array respectively.
Similarly, Rn and Rp denotes the negative and positive part of right sub-array respectively.
Below are the steps to convert [Ln Lp Rn Rp] to [Ln Rn Lp Rp] without using extra space.
1. Reverse Lp and Rn. We get [Lp] -> [Lp'] and [Rn] -> [Rn']
[Ln Lp Rn Rp] -> [Ln Lp’ Rn’ Rp]
1818
Chapter 285. Rearrange positive and negative numbers with constant extra space
1819
Chapter 285. Rearrange positive and negative numbers with constant extra space
RearrangePosNeg(arr, 0, arr_size - 1);
printArray(arr, arr_size);
return 0;
}
Output:
-12 -13 -5 -7 -3 -6 11 6 5
Time complexity of above solution is O(n log n), O(Log n) space for recursive calls, and
no additional data structure.
Source
https://www.geeksforgeeks.org/rearrange-positive-and-negative-numbers/
1820
Chapter 286
1821
Chapter 286. Recursive Bubble Sort
{
for (i = 0; i < n-1; i++)
1822
Chapter 286. Recursive Bubble Sort
// Largest element is fixed,
// recur for remaining array
bubbleSort(arr, n-1);
}
/* Function to print an array */
void printArray(int arr[], int n)
{
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array : \n");
printArray(arr, n);
return 0;
}
Java
1823
Chapter 286. Recursive Bubble Sort
Python3
1824
Chapter 286. Recursive Bubble Sort
C#
1825
Chapter 286. Recursive Bubble Sort
}
}
// This code is contributed
// by Sam007
Output :
Sorted array :
11 12 22 25 34 64 90
Improved By : Sam007
Source
https://www.geeksforgeeks.org/recursive-bubble-sort/
1826
Chapter 287
Example:
1827
Chapter 287. Recursive Insertion Sort
1828
Chapter 287. Recursive Insertion Sort
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
for (int i=0; i < n; i++)
cout << arr[i] <<" ";
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
insertionSortRecursive(arr, n);
printArray(arr, n);
return 0;
}
Java
1829
Chapter 287. Recursive Insertion Sort
Python
1830
Chapter 287. Recursive Insertion Sort
print arr[i],
# Driver program to test insertion sort
arr = [12,11,13,5,6]
n = len(arr)
insertionSortRecursive(arr, n)
printArray(arr, n)
# Contributed by Harsh Valecha
C#
// Recursive C# program
// for insertion sort
using System;
class GFG
{
// Recursive function to sort
// an array using insertion sort
static void insertionSortRecursive(int []arr,
int n)
{
// Base case
if (n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive(arr, n - 1);
// Insert last element at
// its correct position
// in sorted array.
int last = arr[n - 1];
int j = n - 2;
/* Move elements of arr[0..i-1],
that are greater than key, to
one position ahead of their
current position */
while (j >= 0 && arr[j] > last)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = last;
}
1831
Chapter 287. Recursive Insertion Sort
//Driver Code
static void Main()
{
int []arr = {12, 11, 13, 5, 6};
insertionSortRecursive(arr, arr.Length);
for(int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Sam007
PHP
<?php
// Recursive PHP program for insertion sort
// Recursive function to sort an
// array using insertion sort
function insertionSortRecursive(&$arr, $n)
{
// Base case
if ($n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive($arr, $n - 1);
// Insert last element at its correct
// position in sorted array.
$last = $arr[$n - 1];
$j = $n - 2;
// Move elements of arr[0..i-1], that are
// greater than key, to one position ahead
// of their current position
while ($j >= 0 && $arr[$j] > $last)
{
$arr[$j + 1] = $arr[$j];
$j--;
}
$arr[$j + 1] = $last;
}
1832
Chapter 287. Recursive Insertion Sort
Output :
5 6 11 12 13
Source
https://www.geeksforgeeks.org/recursive-insertion-sort/
1833
Chapter 288
The algorithm works by repeatedly finding the minimum element (considering ascending
order) from unsorted part and putting it at the end of sorted part.
arr[] = 64 25 12 22 11
We have already discussed about Iterative Selection Sort. In this article recursive approach
is discussed. The idea of recursive solution is to one by one increment sorted part and
recursively call for remaining (yet to be sorted) part.
1834
Chapter 288. Recursive Selection Sort
C++
1835
Chapter 288. Recursive Selection Sort
Java
1836
Chapter 288. Recursive Selection Sort
}
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 5, 2, 7, 0};
// Calling function
recurSelectionSort(arr, arr.length, 0);
//printing sorted array
for (int i = 0; i< arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Python3
1837
Chapter 288. Recursive Selection Sort
Output:
0 1 2 3 5 7
Source
https://www.geeksforgeeks.org/recursive-selection-sort/
1838
Chapter 289
Recursive selection sort for singly linked list Swapping node links - GeeksforGeeks
Given a singly linked list containing n nodes. The problem is to sort the list using recursive
selection sort technique. The approach should be such that it involves swapping node links
instead of swapping nodes data.
Examples:
In Selection Sort, we first find minimum element, swap it with the beginning node and recur
for remaining list. Below is recursive implementation of these steps for linked list.
recurSelectionSort(head)
if head->next == NULL
return head
Initialize min = head
Initialize beforeMin = NULL
Initialize ptr = head
1839
Chapter 289. Recursive selection sort for singly linked list Swapping node links
ptr = ptr->next
if min != head
swapNodes(&head, head, min, beforeMin)
head->next = recurSelectionSort(head->next)
return head
1840
Chapter 289. Recursive selection sort for singly linked list Swapping node links
1841
Chapter 289. Recursive selection sort for singly linked list Swapping node links
// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
// allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// put in the data
new_node->data = new_data;
// link the old list to the new node
new_node->next = (*head_ref);
// move the head to point to the new node
(*head_ref) = new_node;
}
// function to print the linked list
void printList(struct Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// create linked list 10->12->8->4->6
push(&head, 6);
push(&head, 4);
push(&head, 8);
push(&head, 12);
push(&head, 10);
cout << "Linked list before sorting:n";
printList(head);
// sort the linked list
sort(&head);
cout << "\nLinked list after sorting:n";
printList(head);
1842
Chapter 289. Recursive selection sort for singly linked list Swapping node links
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/recursive-selection-sort-singly-linked-list-swapping-node-links/
1843
Chapter 290
A Naive Approach is to check each element of arr[], after replacing of which makes con-
secutive or not. Time complexity for this approach O(n2 )
A Better Approach is based on an important observation that either the smallest or the
largest element would be answer if answer exists. If answer exists, then there are two cases.
1) Series of consecutive elements starts with minimum element of array then continues by
adding 1 to previous.
1844
Chapter 290. Replacing an element makes array elements consecutive
2) Series of consecutive elements start with maximum element of array, then continues by
subtracting 1 from previous.
We make above two series and for every series, we search series elements in array. If for both
series, number of mismatches are more than 1, then answer does not exist. If any series is
found with one mismatch, then we have answer.
C++
1845
Chapter 290. Replacing an element makes array elements consecutive
}
next_element--;
}
// If only one mismatch is found.
if (mismatch_count2 == 1)
return res;
return -1;
}
// Driver code
int main()
{
int arr[] = {7, 5, 12, 8} ;
int n = sizeof(arr)/sizeof(arr[0]);
int res = findElement(arr,n);
if (res == -1)
cout << "Answer does not exist";
else if (res == 0)
cout << "Elements are already consecutive";
else
cout << res;
return 0;
}
Java
1846
Chapter 290. Replacing an element makes array elements consecutive
for (int i = 0; i < n - 1; i++)
{
if (Arrays.binarySearch(arr,
next_element) < 0)
{
res = arr[0];
mismatch_count1++;
}
next_element++;
}
// If only one mismatch is found.
if (mismatch_count1 == 1)
return res;
// If no mismatch found, elements
// are already consecutive.
if (mismatch_count1 == 0)
return 0;
// Making a series starting
// from last element and
// subtracting 1 to every element.
int mismatch_count2 = 0;
next_element = arr[0] + n - 1;
for (int i = n - 1; i >= 1; i--)
{
if (Arrays.binarySearch(arr,
next_element) < 0)
{
res = arr[n - 1];
mismatch_count2++;
}
next_element--;
}
// If only one mismatch is found.
if (mismatch_count2 == 1)
return res;
return -1;
}
// Driver code
public static void main(String args[])
{
1847
Chapter 290. Replacing an element makes array elements consecutive
C#
1848
Chapter 290. Replacing an element makes array elements consecutive
// If only one mismatch is found.
if (mismatch_count1 == 1)
return res;
// If no mismatch found, elements
// are already consecutive.
if (mismatch_count1 == 0)
return 0;
// Making a series starting
// from last element and
// subtracting 1 to every element.
int mismatch_count2 = 0;
next_element = arr[0] + n - 1;
for (int i = n - 1; i >= 1; i--)
{
if (Array.BinarySearch(arr,
next_element) < 0)
{
res = arr[n - 1];
mismatch_count2++;
}
next_element--;
}
// If only one mismatch is found.
if (mismatch_count2 == 1)
return res;
return -1;
}
// Driver code
static void Main()
{
int []arr = new int[]{7, 5, 12, 8} ;
int n = arr.Length;
int res = findElement(arr,n);
if (res == -1)
Console.Write("Answer does not exist");
else if (res == 0)
Console.Write("Elements are " +
"already consecutive");
else
Console.Write(res);
}
1849
Chapter 290. Replacing an element makes array elements consecutive
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output :
12
Source
https://www.geeksforgeeks.org/replacing-an-element-makes-array-elements-consecutive/
1850
Chapter 291
Input : Ropes[] = { 5, 1, 1, 2, 3, 5 }
Output : 4 3 2
Explanation : In first operation the minimum ropes is 1 so we reduce length 1
from all of them after reducing we left with 4 ropes and we do same for rest.
Input : Ropes[] = { 5, 1, 6, 9, 8, 11, 2, 2, 6, 5 }
Output : 9 7 5 3 2 1
Simple solution is to we traverse a loop from [0…n-1], In each iterations first we find min
length rope. After that we reduce all ropes length by it and then count how many ropes are
left whose length is greater the zero. this process is done until all ropes length is greater
than zero. This solution work in O(n2 ) time.
Efficient solution works in O(nlog(n)). First we have to sort all Ropes in increasing order
of there lenght. after that we have follow the step.
1851
Chapter 291. Ropes left after every removal of smallest
1852
Chapter 291. Ropes left after every removal of smallest
if (singleOperation == 0)
cout << "0 ";
}
int main()
{
int Ropes[] = { 5, 1, 1, 2, 3, 5 };
int n = sizeof(Ropes) / sizeof(Ropes[0]);
cuttringRopes(Ropes, n);
return 0;
}
Java
1853
Chapter 291. Ropes left after every removal of smallest
cuttingLenght = Ropes[i];
singleOperation++;
}
}
// after first operation all ropes
// length become zero
if (singleOperation == 0)
System.out.print("0");
}
public static void main(String[] arg)
{
int[] Ropes = { 5, 1, 1, 2, 3, 5 };
int n = Ropes.length;
cuttringRopes(Ropes, n);
}
}
Python3
# Python 3 program to
# print how many
# Ropes are Left After
# Every Cut
# Function print how many Ropes are
# Left AfterEvery Cutting operation
def cuttringRopes(Ropes, n) :
# sort all Ropes in increase
# of there length
Ropes.sort()
singleOperation = 0
# min length rope
cuttingLenght = Ropes[0]
# now traverse through the given
# Ropes in increase order of length
for i in range(1,n) :
# After cutting if current rope length
# is greater than '0' that mean all
# ropes to it's right side are also
# greater than 0
1854
Chapter 291. Ropes left after every removal of smallest
C#
1855
Chapter 291. Ropes left after every removal of smallest
php
<?php
// PHP program to print how many
// Ropes are Left After Every Cut
// Function print how many Ropes are
// Left AfterEvery Cutting operation
function cuttringRopes($Ropes, $n)
{
// sort all Ropes in increase
// of there length
sort($Ropes);
1856
Chapter 291. Ropes left after every removal of smallest
$singleOperation = 0;
// min length rope
$cuttingLenght = $Ropes[0];
// now traverse through the given
// Ropes in increase order of length
for ($i = 1; $i < $n; $i++)
{
// After cutting if current rope length
// is greater than '0' that mean all
// ropes to it's right side are also
// greater than 0
if ($Ropes[$i] - $cuttingLenght > 0)
{
// print number of ropes remains
echo ($n - $i). " ";
// now current rope become
// min length rope
$cuttingLenght = $Ropes[$i];
$singleOperation++;
}
}
if ($singleOperation == 0)
echo "0 ";
}
// Driver Code
$Ropes = array(5, 1, 1, 2, 3, 5);
$n = count($Ropes);
cuttringRopes($Ropes, $n);
// This code is contributed by Sam007
?>
4 3 2
Source
https://www.geeksforgeeks.org/ropes-left-every-cut/
1857
Chapter 292
Input :
77 11 22 3
11 89 1 12
32 11 56 7
11 22 44 33
Output :
3 11 22 77
1 11 12 89
7 11 32 56
11 22 33 44
Input :
8 6 4 5
3 5 2 1
9 7 4 2
7 8 9 5
Output :
4 5 6 8
1 2 3 5
2 4 7 9
5 7 8 9
1858
Chapter 292. Row wise sorting in 2D array
Output
1859
Chapter 292. Row wise sorting in 2D array
1 7 8 9
0 2 3 7
2 3 5 9
1 2 3 6
Output
1860
Chapter 292. Row wise sorting in 2D array
1 7 8 9
0 2 3 7
2 3 5 9
1 2 3 6
Source
https://www.geeksforgeeks.org/row-wise-sorting-2d-array/
1861
Chapter 293
1862
Chapter 293. Segregate 0s and 1s in an array
Java
1863
Chapter 293. Segregate 0s and 1s in an array
Python3
1864
Chapter 293. Segregate 0s and 1s in an array
# Loop fills remaining arr space with 1
for i in range(count, n) :
arr[i] = 1
# Function to print segregated array
def print_arr(arr , n) :
print( "Array after segregation is ",end = "")
for i in range(0, n) :
print(arr[i] , end = " ")
# Driver function
arr = [ 0, 1, 0, 1, 1, 1 ]
n = len(arr)
segregate0and1(arr, n)
print_arr(arr, n)
# This code is contributed by Nikita Tiwari.
C#
1865
Chapter 293. Segregate 0s and 1s in an array
PHP
<?php
// PHP code to Segregate
// 0s and 1s in an array
// Function to segregate
// 0s and 1s
function segregate0and1(&$arr, $n)
{
$count = 0; // Counts the no
// of zeros in arr
for ($i = 0; $i < $n; $i++)
{
if ($arr[$i] == 0)
$count++;
}
// Loop fills the arr
// with 0 until count
for ($i = 0; $i < $count; $i++)
1866
Chapter 293. Segregate 0s and 1s in an array
$arr[$i] = 0;
// Loop fills remaining
// arr space with 1
for ($i = $count; $i < $n; $i++)
$arr[$i] = 1;
}
// Function to print
// segregated array
function toprint(&$arr , $n)
{
echo ("Array after segregation is ");
for ($i = 0; $i < $n; $i++)
echo ( $arr[$i] . " ");
}
// Driver Code
$arr = array(0, 1, 0, 1, 1, 1 );
$n = sizeof($arr);
segregate0and1($arr, $n);
toprint($arr, $n);
// This code is contributed
// by Shivi_Aggarwal
?>
Output :
The method 1 traverses the array two times. Method 2 does the same in a single pass.
Method 2 (Use two indexes to traverse)
Maintain two indexes. Initialize first index left as 0 and second index right as n-1.
Do following while left < right
a) Keep incrementing index left while there are 0s at it
b) Keep decrementing index right while there are 1s at it
c) If left < right then exchange arr[left] and arr[right]
Implementation:
C/C++
1867
Chapter 293. Segregate 0s and 1s in an array
#include<stdio.h>
/*Function to put all 0s on left and all 1s on right*/
void segregate0and1(int arr[], int size)
{
/* Initialize left and right indexes */
int left = 0, right = size-1;
while (left < right)
{
/* Increment left index while we see 0 at left */
while (arr[left] == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while (arr[right] == 1 && left < right)
right--;
/* If left is smaller than right then there is a 1 at left
and a 0 at right. Exchange arr[left] and arr[right]*/
if (left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
/* driver program to test */
int main()
{
int arr[] = {0, 1, 0, 1, 1, 1};
int i, arr_size = sizeof(arr)/sizeof(arr[0]);
segregate0and1(arr, arr_size);
printf("Array after segregation ");
for (i = 0; i < 6; i++)
printf("%d ", arr[i]);
getchar();
return 0;
}
Java
1868
Chapter 293. Segregate 0s and 1s in an array
class Segregate
{
/*Function to put all 0s on left and all 1s on right*/
void segregate0and1(int arr[], int size)
{
/* Initialize left and right indexes */
int left = 0, right = size - 1;
while (left < right)
{
/* Increment left index while we see 0 at left */
while (arr[left] == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while (arr[right] == 1 && left < right)
right--;
/* If left is smaller than right then there is a 1 at left
and a 0 at right. Exchange arr[left] and arr[right]*/
if (left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
/* Driver Program to test above functions */
public static void main(String[] args)
{
Segregate seg = new Segregate();
int arr[] = new int[]{0, 1, 0, 1, 1, 1};
int i, arr_size = arr.length;
seg.segregate0and1(arr, arr_size);
System.out.print("Array after segregation is ");
for (i = 0; i < 6; i++)
System.out.print(arr[i] + " ");
}
}
Python
1869
Chapter 293. Segregate 0s and 1s in an array
# Function to put all 0s on left and all 1s on right
def segregate0and1(arr, size):
# Initialize left and right indexes
left, right = 0, size-1
while left < right:
# Increment left index while we see 0 at left
while arr[left] == 0 and left < right:
left += 1
# Decrement right index while we see 1 at right
while arr[right] == 1 and left < right:
right -= 1
# If left is smaller than right then there is a 1 at left
# and a 0 at right. Exchange arr[left] and arr[right]
if left < right:
arr[left] = 0
arr[right] = 1
left += 1
right -= 1
return arr
# driver program to test
arr = [0, 1, 0, 1, 1, 1]
arr_size = len(arr)
print("Array after segregation")
print(segregate0and1(arr, arr_size))
# This code is contributed by Pratik Chhajer
C#
1870
Chapter 293. Segregate 0s and 1s in an array
{
/* Increment left index while
we see 0 at left */
while (arr[left] == 0 && left < right)
left++;
/* Decrement right index while
we see 1 at right */
while (arr[right] == 1 && left < right)
right--;
/* If left is smaller than right then
there is a 1 at left and a 0 at right.
Exchange arr[left] and arr[right]*/
if (left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
/* Driver Program to test above functions */
public static void Main()
{
Segregate seg = new Segregate();
int []arr = new int[]{0, 1, 0, 1, 1, 1};
int i, arr_size = arr.Length;
seg.segregate0and1(arr, arr_size);
Console.WriteLine("Array after segregation is ");
for (i = 0; i < 6; i++)
Console.Write(arr[i] + " ");
}
}
//This code is contributed by vt_m.
PHP
<?php
// PHP program to sort a
// binary array in one pass
// Function to put all 0s on
1871
Chapter 293. Segregate 0s and 1s in an array
1872
Chapter 293. Segregate 0s and 1s in an array
?>
Output:
1873
Chapter 293. Segregate 0s and 1s in an array
Java
1874
Chapter 293. Segregate 0s and 1s in an array
}
}
}
Python 3
PHP
<?php
// PHP program to sort a
// binary array in one pass
// Function to put all 0s on
// left and all 1s on right
function segregate0and1(&$arr , $size)
{
1875
Chapter 293. Segregate 0s and 1s in an array
$type0 = 0;
$type1 = $size - 1;
while($type0 < $type1)
{
if($arr[$type0] == 1)
{
$temp = $arr[$type0];
$arr[$type0] = $arr[$type1];
$arr[$type1] = $temp;
$type1--;
}
else
$type0++;
}
}
// Driver Code
$arr = array(0, 1, 0, 1, 1, 1);
$arr_size = sizeof($arr);
segregate0and1($arr, $arr_size);
echo ("Array after segregation is ");
for ($i = 0; $i < $arr_size; $i++)
echo ($arr[$i] . " ");
// This code is contributed
// by Shivi_Aggarwal
?>
Output:
1876
Chapter 293. Segregate 0s and 1s in an array
Source
https://www.geeksforgeeks.org/segregate-0s-and-1s-in-an-array-by-traversing-array-once/
1877
Chapter 294
Input : 1 9 5 3 2 6 7 11
Output : 2 6 5 3 1 9 7 11
Input : 1 3 2 4 7 6 9 10
Output : 2 4 6 10 7 1 9 3
1. Maintain a pointer to the position before first odd element in the array.
2. Traverse the array and if even number is encountered then swap it with the first odd
element.
3. Continue the traversal.
C++
1878
Chapter 294. Segregate even and odd numbers Set 3
Java
1879
Chapter 294. Segregate even and odd numbers Set 3
while (j != n) {
if (arr[j] % 2 == 0)
{
i++;
// Swapping even and
// odd numbers
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j++;
}
// Printing segregated array
for (int k = 0; k < n; k++)
System.out.print(arr[k] + " ");
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 3, 2, 4, 7,
6, 9, 10 };
int n = arr.length;
arrayEvenAndOdd(arr, n);
}
}
// This code is contributed by Sam007
C#
1880
Chapter 294. Segregate even and odd numbers Set 3
{
i++;
// Swapping even and
// odd numbers
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j++;
}
// Printing segregated array
for (int k = 0; k < n; k++)
Console.Write(arr[k] + " ");
}
// Driver code
static void Main()
{
int []arr = { 1, 3, 2, 4, 7,
6, 9, 10 };
int n = arr.Length;
arrayEvenAndOdd(arr, n);
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP code to segregate even odd
// numbers in an array
// Function to segregate
// even odd numbers
function arrayEvenAndOdd($arr, $n)
{
$i = -1;
$j = 0;
$t;
while ($j != $n)
{
if ($arr[$j] % 2 == 0)
{
$i++;
1881
Chapter 294. Segregate even and odd numbers Set 3
Output:
2 4 6 10 7 1 9 3
Source
https://www.geeksforgeeks.org/segregate-even-odd-numbers-set-3/
1882
Chapter 295
Selection Sort
arr[] = 64 25 12 22 11
C/C++
1883
Chapter 295. Selection Sort
1884
Chapter 295. Selection Sort
Python
Java
1885
Chapter 295. Selection Sort
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Prints the array
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver code to test above
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
/* This code is contributed by Rajat Mishra*/
C#
1886
Chapter 295. Selection Sort
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Prints the array
static void printArray(int []arr)
{
int n = arr.Length;
for (int i=0; i<n; ++i)
Console.Write(arr[i]+" ");
Console.WriteLine();
}
// Driver code
public static void Main()
{
int []arr = {64,25,12,22,11};
sort(arr);
Console.WriteLine("Sorted array");
printArray(arr);
}
}
// This code is contributed by Sam007
Output:
Sorted array:
11 12 22 25 64
Snapshots:
1887
Chapter 295. Selection Sort
1888
Chapter 295. Selection Sort
Source
https://www.geeksforgeeks.org/selection-sort/
1889
Chapter 296
In Java 8, there is a new API introduced for sorting which is Parallel Sorting.
Parallel Sort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to
multiple threads available in the thread pool. Fork/Join implements a work stealing algo-
rithm where in a idle thread can steal tasks queued up in another thread.
For Example, the following code is a program that sorts a randomized array of doubles
using Arrays.sort() and Arrays.parallelSort(). This program simply measures the per-
formance difference between this two approaches. :
1890
Chapter 296. Serial Sort v/s Parallel Sort in Java
double[] result = new double[size];
for (int i = 0; i < size; i++)
result[i] = Math.random();
return result;
}
// Driver code to compare two sortings
public static void main(String[] args)
{
for (int i = 1; i < 10000; i *= 10)
{
int size = BASE_ARRAY_SIZE * i;
double[] arr1 = generateArray(size);
// Creating a copy of arr1 so that we can
// use same content for both sortings.
double[] arr2 = Arrays.copyOf(arr1, arr1.length);
System.out.println("Array Size: " + size);
// Sorting arr1[] using serial sort
long startTime = System.currentTimeMillis();
Arrays.sort(arr1);
long endTime = System.currentTimeMillis();
System.out.println("Time take in serial: " +
(endTime - startTime) + "ms.");
// Sorting arr2[] using serial sort
startTime = System.currentTimeMillis();
Arrays.parallelSort(arr2);
endTime = System.currentTimeMillis();
System.out.println("Time take in parallel: "
+ (endTime - startTime) + "ms.");
System.out.println();
}
}
}
Environment :
Note : Required Time may vary due to random values in the array.
The key differences between both the algorithm are as follow :
1891
Chapter 296. Serial Sort v/s Parallel Sort in Java
Analysis :
The results show that parallel sorting on a multicore machine can achieve performance
improvements at 1 million or more elements. While below this threshold it may actually be
slower than sequential sorting. This result meets the expectation, and the suitable size here
may be 1 million. Your mileage may vary, it depends on your environment.
Explanation :
Now, let’s take a look at the code to figure out how this parallel sorting works.
When the array length reaches a minimum granularity and you got more than 1 worker
thread, the array is sorted using the parallel sort method. And the ForkJoin common
pool is used to execute parallel tasks here.
1892
Chapter 296. Serial Sort v/s Parallel Sort in Java
Reference :
http://download.java.net/lambda/b84/docs/api/java/util/Arrays.html#parallelSort%
28int
Source
https://www.geeksforgeeks.org/serial-sort-vs-parallel-sort-java/
1893
Chapter 297
ShellSort
ShellSort - GeeksforGeeks
ShellSortis mainly a variation of Insertion Sort. In insertion sort, we move elements only
one position ahead. When an element has to be moved far ahead, many movements are
involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the
array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1.
An array is said to be h-sorted if all sublists of every h’th element is sorted.
Following is the implementation of ShellSort.
C++
1894
Chapter 297. ShellSort
Java
1895
Chapter 297. ShellSort
1896
Chapter 297. ShellSort
Python
1897
Chapter 297. ShellSort
C#
// C# implementation of ShellSort
using System;
class ShellSort
{
/* An utility function to
print array of size n*/
static void printArray(int []arr)
{
int n = arr.Length;
for (int i=0; i<n; ++i)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
/* function to sort arr using shellSort */
int sort(int []arr)
{
int n = arr.Length;
// Start with a big gap,
// then reduce the gap
for (int gap = n/2; gap > 0; gap /= 2)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements a[0..gap-1] are already
// in gapped order keep adding one more element
// until the entire array is gap sorted
for (int i = gap; i < n; i += 1)
{
// add a[i] to the elements that have
// been gap sorted save a[i] in temp and
// make a hole at position i
int temp = arr[i];
// shift earlier gap-sorted elements up until
// the correct location for a[i] is found
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
// put temp (the original a[i])
// in its correct location
arr[j] = temp;
1898
Chapter 297. ShellSort
}
}
return 0;
}
// Driver method
public static void Main()
{
int []arr = {12, 34, 54, 2, 3};
Console.Write("Array before sorting :\n");
printArray(arr);
ShellSort ob = new ShellSort();
ob.sort(arr);
Console.Write("Array after sorting :\n");
printArray(arr);
}
}
// This code is contributed by nitin mittal.
Output:
Snapshots:
1899
Chapter 297. ShellSort
1900
Chapter 297. ShellSort
1901
Chapter 297. ShellSort
1902
Chapter 297. ShellSort
1903
Chapter 297. ShellSort
1904
Chapter 297. ShellSort
1905
Chapter 297. ShellSort
• Selection Sort
• Bubble Sort
• Insertion Sort
• Merge Sort
• Heap Sort
• QuickSort
• Radix Sort
• Counting Sort
• Bucket Sort
Source
https://www.geeksforgeeks.org/shellsort/
1906
Chapter 298
Input : n = 5
7 9 10 8 11
Output : 3
Explanation : 9 10 8 unordered sub array.
Input : n = 5
1 2 3 4 5
Output : 0
Explanation : Array is in increasing order.
The idea is based on the fact that size of shortest subarray would be either 0 or 3. We have to
check array element is either increasing or decreasing, if all array elements are in increasing
or decreasing, then length of shortest sub array is 0, And if either the array element is not
follow the increasing or decreasing then it shortest length is 3.
C++
1907
Chapter 298. Shortest Un-ordered Subarray
{
for (int i = 0; i < n - 1; i++)
if (a[i] >= a[i + 1])
return false;
return true;
}
// bool function for checking an array
// elements are in decreasing.
bool decreasing(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
if (a[i] < a[i + 1])
return false;
return true;
}
int shortestUnsorted(int a[], int n)
{
// increasing and decreasing are two functions.
// if function return true value then print
// 0 otherwise 3.
if (increasing(a, n) == true ||
decreasing(a, n) == true)
return 0;
else
return 3;
}
// Driver code
int main()
{
int ar[] = { 7, 9, 10, 8, 11 };
int n = sizeof(ar) / sizeof(ar[0]);
cout << shortestUnsorted(ar, n);
return 0;
}
Java
1908
Chapter 298. Shortest Un-ordered Subarray
Python3
1909
Chapter 298. Shortest Un-ordered Subarray
C#
1910
Chapter 298. Shortest Un-ordered Subarray
// boolean function to check
// array elements are in the
// increasing order or not
public static bool increasing(int[] a, int n)
{
for (int i = 0; i < n - 1; i++)
if (a[i] >= a[i + 1])
return false;
return true;
}
// boolean function to check
// array elements are in the
// decreasing order or not
public static bool decreasing(int[] arr, int n)
{
for (int i = 0; i < n - 1; i++)
if (arr[i] < arr[i + 1])
return false;
return true;
}
public static int shortestUnsorted(int[] a, int n)
{
// increasing and decreasing are
// two functions. function return
// true value then print 0 else 3
if (increasing(a, n) == true ||
decreasing(a, n) == true)
return 0;
else
return 3;
}
// Driver program
public static void Main()
{
int[] ar = new int[] { 7, 9, 10, 8, 11 };
int n = ar.Length;
Console.WriteLine(shortestUnsorted(ar, n));
}
}
1911
Chapter 298. Shortest Un-ordered Subarray
PHP
<?php
// php program to find shortest
// subarray which is unsorted.
// bool function for checking an
// array elements are in increasing.
function increasing($a, $n)
{
for ( $i = 0; $i < $n - 1; $i++)
if ($a[$i] >= $a[$i + 1])
return false;
return true;
}
// bool function for checking an
// array elements are in decreasing.
function decreasing($a, $n)
{
for ($i = 0; $i < $n - 1; $i++)
if ($a[$i] < $a[$i + 1])
return false;
return true;
}
function shortestUnsorted($a, $n)
{
// increasing and decreasing are
// two functions. if function
// return true value then print
// 0 otherwise 3.
if (increasing($a, $n) == true ||
decreasing($a, $n) == true)
return 0;
else
return 3;
}
// Driver code
$ar = array( 7, 9, 10, 8, 11 );
$n = sizeof($ar);
echo shortestUnsorted($ar, $n);
1912
Chapter 298. Shortest Un-ordered Subarray
Output :
Source
https://www.geeksforgeeks.org/shortest-un-ordered-subarray/
1913
Chapter 299
INPUT: 8 2 9
3s: sleep 8
6s: sleep 2
8s: "2" (2 wakes up so print it)
9s: sleep 9
11s: "8" (8 wakes up so print it)
18s: "9" (9 wakes up so print it)
OUTPUT: 2 8 9
1914
Chapter 299. Sleep Sort – The King of Laziness / Sorting while Sleeping
Implementation
To implement sleep sort, we need multithreading functions, such as _beginthread() and
WaitForMultipleObjects(). Hence we need to include windows.h to use these functions.
This won’t compile on Online IDE. We must run it in your PC (Note this code is for
WINDOWS and not for LINUX).
To perform a sleep sort we need to create threads for each of the value in the input array.
We do this using the function _beginthread().
In each of the threads we assign two instructions:
1) Sleep : Sleep this thread till arr[i] milliseconds (where arr[i] is the array element which
this thread is associated to). We do this using Sleep() function. The Sleep(n) function
suspends the activity associated with this thread till ‘n’ milliseconds. Hence if we write
Sleep(1000), then it means that the thread will sleep for 1 second (1000 milliseconds = 1
second)
2) Print : When the thread ‘wakes’ up after the sleep then print the array element – arr[i]
which this thread is associated to.
After creating the threads, we process these threads. We do this using WaitForMulti-
pleObjects().
1915
Chapter 299. Sleep Sort – The King of Laziness / Sorting while Sleeping
1916
Chapter 299. Sleep Sort – The King of Laziness / Sorting while Sleeping
{
// Doesn't work for negative numbers
int arr[] = {34, 23, 122, 9};
int n = sizeof(arr) / sizeof(arr[0]);
sleepSort (arr, n);
return(0);
}
Limitations
1) This algorithm won’t work for negative numbers as a thread cannot sleep for a negative
amount of time.
2) Since this algorithm depends on the input elements, so a huge number in the input array
causes this algorithm to slow down drastically (as the thread associated with that number
has to sleep for a long time). So even if the input array element contains only 2 elements,
like- {1, 100000000}, then also we have to wait for a much longer duration to sort.
3) This algorithm doesn’t produce a correct sorted output every time. This generally hap-
pens when there is a very small number to the left of a very large number in the input array.
For example – {34, 23, 1, 12253, 9}.
The output after sleep sorting is {9, 1, 23, 34, 1223}
A wrong output also occurs when the input array is reverse sorted initially, like- {10, 9, 8,
7, 6, 5}.
The reason for such an unexpected output is because some time is taken between scanning
through each element as well as some other OS operations (like inserting each threads in a
priority queue for scheduling). We cannot simply ignore the time taken by all these things.
We describe this using the below example-
1917
Chapter 299. Sleep Sort – The King of Laziness / Sorting while Sleeping
3s: sleep 10
6s: sleep 9
9s: sleep 8
12s: sleep 7
13s: "10" (10 wakes up so print it)
15s: sleep 6
15s: "9" (9 wakes up so print it)
17s: "8" (8 wakes up so print it)
18s: sleep 5
19s: "7" (7 wakes up so print it)
21s: "6" (6 wakes up so print it)
23s: "5" (5 wakes up so print it)
OUTPUT: 10 9 8 7 6 5
1918
Chapter 299. Sleep Sort – The King of Laziness / Sorting while Sleeping
1) The above algorithm tries to sort it in ascending order. Can you sort an input array in
descending order using sleep sort. Think upon it.
2) Is it a comparison based sorting algorithm ? How many comparisons this algorithm makes
?
[ Answer : No, it makes zero comparisons ]
3) Can we do sleeping sort without using windows.h header and without using Sleep()
function?
[One idea can be to create a priority queue where the elements are arranged according to
the time left before waking up and getting printed. The element at the front of the priority
queue will be the first one to get waked up. However the implementation doesn’t looks easy.
Think on it.]
Time Complexity
Although there are many conflicting opinions about the time complexity of sleep sort, but
we can approximate the time complexity using the below reasoning-
Since Sleep() function and creating multiple threads is done internally by the OS using a
priority queue (used for scheduling purposes). Hence inserting all the array elements in
the priority queue takes O(Nlog N) time. Also the output is obtained only when all the
threads are processed, i.e- when all the elements ‘wakes’ up. Since it takes O(arr[i]) time to
wake the ith array element’s thread. So it will take a maximum of O(max(input)) for the
largest element of the array to wake up. Thus the overall time complexity can be assumed
as O(NlogN + max(input)),
where, N = number of elements in the input array, and input = input array elements
Auxiliary Space
All the things are done by the internal priority queue of the OS. Hence auxiliary space can
be ignored.
Conclusion
Sleep Sort is related to Operating System more than any other sorting algorithm. This
sorting algorithm is a perfect demonstration of multi-threading and scheduling done by OS.
The phrase “Sorting while Sleeping” itself sounds very unique. Overall it is a fun, lazy, weird
algorithm. But as rightly said by someone- “If it works then it is not lazy”.
Source
https://www.geeksforgeeks.org/sleep-sort-king-laziness-sorting-sleeping/
1919
Chapter 300
1920
Chapter 300. Smallest Difference Triplet from Three arrays
3. Now find min and max and calculate max-min from these three elements.
4. Now increment pointer of minimum element’s array.
5. Repeat steps 2, 3, 4, for the new set of pointers until any one pointer reaches to its
end.
C++
1921
Chapter 300. Smallest Difference Triplet from Three arrays
Java
1922
Chapter 300. Smallest Difference Triplet from Three arrays
{
return Math.max(Math.max(a, b), c);
}
// function to find minimum number
static int minimum(int a, int b, int c)
{
return Math.min(Math.min(a, b), c);
}
// Finds and prints the smallest Difference
// Triplet
static void smallestDifferenceTriplet(int arr1[],
int arr2[], int arr3[], int n)
{
// sorting all the three arrays
Arrays.sort(arr1);
Arrays.sort(arr2);
Arrays.sort(arr3);
// To store resultant three numbers
int res_min=0, res_max=0, res_mid=0;
// pointers to arr1, arr2, arr3
// respectively
int i = 0, j = 0, k = 0;
// Loop until one array reaches to its end
// Find the smallest difference.
int diff = 2147483647;
while (i < n && j < n && k < n)
{
int sum = arr1[i] + arr2[j] + arr3[k];
// maximum number
int max = maximum(arr1[i], arr2[j], arr3[k]);
// Find minimum and increment its index.
int min = minimum(arr1[i], arr2[j], arr3[k]);
if (min == arr1[i])
i++;
else if (min == arr2[j])
j++;
else
k++;
1923
Chapter 300. Smallest Difference Triplet from Three arrays
Python3
1924
Chapter 300. Smallest Difference Triplet from Three arrays
# sorting all the three arrays
arr1.sort()
arr2.sort()
arr3.sort()
# To store resultant three numbers
res_min = 0; res_max = 0; res_mid = 0
# pointers to arr1, arr2,
# arr3 respectively
i = 0; j = 0; k = 0
# Loop until one array reaches to its end
# Find the smallest difference.
diff = 2147483647
while (i < n and j < n and k < n):
sum = arr1[i] + arr2[j] + arr3[k]
# maximum number
max = maximum(arr1[i], arr2[j], arr3[k])
# Find minimum and increment its index.
min = minimum(arr1[i], arr2[j], arr3[k])
if (min == arr1[i]):
i += 1
elif (min == arr2[j]):
j += 1
else:
k += 1
# Comparing new difference with the
# previous one and updating accordingly
if (diff > (max - min)):
diff = max - min
res_max = max
res_mid = sum - (max + min)
res_min = min
# Print result
print(res_max, ",", res_mid, ",", res_min)
# Driver code
arr1 = [5, 2, 8]
arr2 = [10, 7, 12]
arr3 = [9, 14, 6]
1925
Chapter 300. Smallest Difference Triplet from Three arrays
n = len(arr1)
smallestDifferenceTriplet(arr1, arr2, arr3, n)
# This code is contributed by Anant Agarwal.
C#
// C# implementation of smallest
// difference triplet
using System;
class GFG
{
// function to find
// maximum number
static int maximum(int a, int b, int c)
{
return Math.Max(Math.Max(a, b), c);
}
// function to find
// minimum number
static int minimum(int a, int b, int c)
{
return Math.Min(Math.Min(a, b), c);
}
// Finds and prints the
// smallest Difference Triplet
static void smallestDifferenceTriplet(int []arr1,
int []arr2,
int []arr3,
int n)
{
// sorting all the
// three arrays
Array.Sort(arr1);
Array.Sort(arr2);
Array.Sort(arr3);
// To store resultant
// three numbers
int res_min = 0, res_max = 0, res_mid = 0;
// pointers to arr1, arr2,
// arr3 respectively
1926
Chapter 300. Smallest Difference Triplet from Three arrays
int i = 0, j = 0, k = 0;
// Loop until one array
// reaches to its end
// Find the smallest difference.
int diff = 2147483647;
while (i < n && j < n && k < n)
{
int sum = arr1[i] +
arr2[j] + arr3[k];
// maximum number
int max = maximum(arr1[i],
arr2[j], arr3[k]);
// Find minimum and
// increment its index.
int min = minimum(arr1[i],
arr2[j], arr3[k]);
if (min == arr1[i])
i++;
else if (min == arr2[j])
j++;
else
k++;
// comparing new difference
// with the previous one and
// updating accordingly
if (diff > (max - min))
{
diff = max - min;
res_max = max;
res_mid = sum - (max + min);
res_min = min;
}
}
// Print result
Console.WriteLine(res_max + ", " +
res_mid + ", " +
res_min);
}
// Driver code
static public void Main ()
{
1927
Chapter 300. Smallest Difference Triplet from Three arrays
PHP
<?php
// PHP implementation of
// smallest difference triplet
// function to find
// maximum number
function maximum($a, $b, $c)
{
return max(max($a, $b), $c);
}
// function to find
// minimum number
function minimum($a, $b, $c)
{
return min(min($a, $b), $c);
}
// Finds and prints the
// smallest Difference Triplet
function smallestDifferenceTriplet($arr1, $arr2,
$arr3, $n)
{
// sorting all the
// three arrays
sort($arr1);
sort($arr2);
sort($arr3);
// To store resultant
// three numbers
$res_min; $res_max; $res_mid;
1928
Chapter 300. Smallest Difference Triplet from Three arrays
1929
Chapter 300. Smallest Difference Triplet from Three arrays
// Driver Code
$arr1 = array(5, 2, 8);
$arr2 = array(10, 7, 12);
$arr3 = array(9, 14, 6);
$n = sizeof($arr1);
smallestDifferenceTriplet($arr1, $arr2,
$arr3, $n);
// This code is contributed by ajit
?>
Output :
7, 6, 5
Source
https://www.geeksforgeeks.org/smallest-difference-triplet-from-three-arrays/
1930
Chapter 301
A simple solution is to Brute Force using two loops with Time Complexity O(n2 ).
A better solution is to sort the arrays. Once the arrays are sorted, we can find the
minimum difference by iterating through the arrays using the approach discussed in below
post.
Find the closest pair from two sorted arrays
Consider the following two arrays:
A: {l, 2, 11, 15}
B: {4, 12, 19, 23, 127, 235}
1931
Chapter 301. Smallest Difference pair of values between two unsorted Arrays
1. Suppose a pointer a points to the beginning of A and a pointer b points to the beginning
of B. The current difference between a and bis 3. Store this as the min.
2. How can we (potentially) make this difference smaller? Well, the value at bis bigger
than the value at a, so moving b will only make the difference larger. Therefore, we want
to move a.
3. Now a points to 2 and b (still) points to 4. This difference is 2, so we should update min.
Move a, since it is smaller.
4. Now a points to 11 and b points to 4. Move b.
5. Now a points to 11 and b points to 12. Update min to 1. Move b. And so on.
Below is the implementation of the idea.
C++
1932
Chapter 301. Smallest Difference pair of values between two unsorted Arrays
}
// return final sma result
return result;
}
// Driver Code
int main()
{
// Input given array A
int A[] = {1, 2, 11, 5};
// Input given array B
int B[] = {4, 12, 19, 23, 127, 235};
// Calculate size of Both arrays
int m = sizeof(A) / sizeof(A[0]);
int n = sizeof(B) / sizeof(B[0]);
// Call function to print
// smallest result
cout << findSmallestDifference(A, B, m, n);
return 0;
}
Java
1933
Chapter 301. Smallest Difference pair of values between two unsorted Arrays
Python3
1934
Chapter 301. Smallest Difference pair of values between two unsorted Arrays
1935
Chapter 301. Smallest Difference pair of values between two unsorted Arrays
# Call function to
# print smallest result
print(findSmallestDifference(A, B, m, n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
1936
Chapter 301. Smallest Difference pair of values between two unsorted Arrays
PHP
<?php
// PHP Code to find Smallest
// Difference between two Arrays
// function to calculate Small
// result between two arrays
function findSmallestDifference($A, $B,
$m, $n)
{
// Sort both arrays
// using sort function
sort($A);
sort($A, $m);
sort($B);
sort($B, $n);
1937
Chapter 301. Smallest Difference pair of values between two unsorted Arrays
$a = 0; $b = 0;
$INT_MAX = 1;
// Initialize result
// as max value
$result = $INT_MAX;
// Scan Both Arrays upto
// sizeof of the Arrays
while ($a < $m && $b < $n)
{
if (abs($A[$a] - $B[$b]) < $result)
$result = abs($A[$a] - $B[$b]);
// Move Smaller Value
if ($A[$a] < $B[$b])
$a++;
else
$b++;
}
// return final sma result
return $result;
}
// Driver Code
{
// Input given array A
$A = array(1, 2, 11, 5);
// Input given array B
$B = array(4, 12, 19, 23, 127, 235);
// Calculate size of Both arrays
$m = sizeof($A) / sizeof($A[0]);
$n = sizeof($B) / sizeof($B[0]);
// Call function to print
// smallest result
echo findSmallestDifference($A, $B, $m, $n);
return 0;
}
// This code is contributed by nitin mittal.
1938
Chapter 301. Smallest Difference pair of values between two unsorted Arrays
?>
Output :
This algorithm takes O(m log m + n log n) time to sort and O(m + n) time to find the
minimum difference. Therefore, the overall runtime is O(m log m + n log n).
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/smallest-difference-pair-values-two-unsorted-arrays/
1939
Chapter 302
Input : arr[] = {2 2 1 3 1}
k = 2
Output: 1
Explanation:
Here in array,
2 is repeated 2 times
1 is repeated 2 times
3 is repeated 1 time
Hence 2 and 1 both are repeated 'k' times
i.e 2 and min(2, 1) is 1
Input : arr[] = {3 5 3 2}
k = 1
Output : 2
Explanation:
Both 2 and 5 are repeating 1 time but
min(5, 2) is 2
Simple Approach: A simple approach is to use two nested loops.The outer loop picks an
1940
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
element one by one starting from the leftmost element. The inner loop checks if the same
element is present on right side of it. If present increase the count and make the number
negative which we got at the right side to prevent it from counting again.
C++
Java
1941
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
Python3
1942
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
MAX = 1000
def findDuplicate(arr, n, k):
# Since arr[] has numbers in
# range from 1 to MAX
res = MAX + 1
for i in range(0, n):
if (arr[i] > 0):
# set count to 1 as number
# is present once
count = 1
for j in range(i + 1, n):
if (arr[i] == arr[j]):
count += 1
# If frequency of number is equal to 'k'
if (count == k):
res = min(res, arr[i])
return res
# Driver code
arr = [2, 2, 1, 3, 1]
k = 2
n = len(arr)
print(findDuplicate(arr, n, k))
# This code is contributed by Smitha Dinesh Semwal.
C#
1943
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
// Since arr[] has numbers in range
// from 1 to MAX
int res = MAX + 1;
for (int i = 0; i < n; i++)
{
if (arr[i] > 0)
{
// set count to 1 as number
// is present once
int count = 1;
for (int j = i + 1; j < n; j++)
if (arr[i] == arr[j])
count += 1;
// If frequency of number is
// equal to 'k'
if (count == k)
res = Math.Min(res, arr[i]);
}
}
return res;
}
// Driver code
public static void Main()
{
int[] arr = { 2, 2, 1, 3, 1 };
int k = 2;
int n = arr.Length;
Console.WriteLine(
findDuplicate(arr, n, k));
}
}
// This article is contributed by vt_m.
Output:
1944
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
Java
1945
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
Python
1946
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
C#
1947
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
while (i < n) {
int j, count = 1;
for (j = i + 1; j < n &&
arr[j] == arr[i]; j++)
count++;
if (count == k)
return arr[i];
i = j;
}
return -1;
}
// Driver code
public static void Main()
{
int[] arr = { 2, 2, 1, 3, 1 };
int k = 2;
int n = arr.Length;
Console.WriteLine(
findDuplicate(arr, n, k));
}
}
// This article is contributed by vt_m.
Output:
1948
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
Java
1949
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
Python
1950
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
C#
1951
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
Output:
1952
Chapter 302. Smallest element in an array that is repeated exactly ‘k’ times.
Source
https://www.geeksforgeeks.org/smallest-element-array-repeated-exactly-k-times/
1953
Chapter 303
Input : 6 3 9 8 10 2 1 15 7
Output : 7 6 10 9 15 3 2 _ 8
Here every element of array has next greater
element but at index 7,
15 is the greatest element of given array
and no other element is greater from 15
so at the index of 15 we fill with '_' .
Input : 13 6 7 12
Output : _ 7 12 13
Here, at index 0, 13 is the greatest
value in given array and no other
array element is greater from 13 so
at index 0 we fill '_'.
Asked in : Zoho
A simple solution is to use two loops nested. The outer loop picks all elements one by one
and inner loop finds the next greater element by linearly searching from beginning to end.
C++
1954
Chapter 303. Smallest greater elements in whole array
Java
1955
Chapter 303. Smallest greater elements in whole array
{
for (int i = 0; i < n; i++)
{
// Find the closest greater
// element for arr[j] in
// the entire array.
int diff = Integer.MAX_VALUE;
int closest = -1;
for (int j = 0; j < n; j++)
{
if (arr[i] < arr[j] &&
arr[j] - arr[i] < diff)
{
diff = arr[j] - arr[i];
closest = j;
}
}
// Check if arr[i] is largest
if(closest == -1)
System.out.print( "_ " );
else
System.out.print(arr[closest] + " ");
}
}
// Driver code
public static void main (String[] args)
{
int ar[] = {6, 3, 9, 8, 10,
2, 1, 15, 7};
int n = ar.length;
smallestGreater(ar, n);
}
}
// This code is contributed by anuj_67.
Python3
1956
Chapter 303. Smallest greater elements in whole array
C#
1957
Chapter 303. Smallest greater elements in whole array
{
diff = arr[j] - arr[i];
closest = j;
}
}
// Check if arr[i] is largest
if(closest == -1)
Console.Write( "_ " );
else
Console.Write(arr[closest] + " ");
}
}
// Driver code
public static void Main()
{
int []ar = {6, 3, 9, 8, 10,
2, 1, 15, 7};
int n = ar.Length;
smallestGreater(ar, n);
}
}
// This code is contributed by anuj_67.
PHP
<?php
// Simple PHP program to find smallest
// greater element in whole array for
// every element.
function smallestGreater($arr, $n)
{
for ( $i = 0; $i < $n; $i++) {
// Find the closest greater element
// for arr[j] in the entire array.
$diff = PHP_INT_MAX; $closest = -1;
for ( $j = 0; $j < $n; $j++) {
if ( $arr[$i] < $arr[$j] &&
$arr[$j] - $arr[$i] < $diff)
{
$diff = $arr[$j] - $arr[$i];
$closest = $j;
}
}
1958
Chapter 303. Smallest greater elements in whole array
// Check if arr[i] is largest
if ($closest == -1)
echo "_ " ;
else
echo $arr[$closest] , " ";
}
}
// Driver code
$ar = array (6, 3, 9, 8, 10, 2, 1, 15, 7);
$n = sizeof($ar) ;
smallestGreater($ar, $n);
// This code is contributed by ajit
?>
Output:
7 6 10 9 15 3 2 _ 8
1959
Chapter 303. Smallest greater elements in whole array
Output :
7 6 10 9 15 3 2 _ 8
Time Complexity : O(n Log n). Note that self balancing search tree (implemented by
set in C++) insert operations take O(Log n) time to insert and find.
Auxiliary Space: O(n)
We can also use sorting followed bybinary searches to solve the above problem in same time
and same auxiliary space.
Improved By : jit_t, vt_m, manishshaw1
Source
https://www.geeksforgeeks.org/smallest-greater-elements-in-whole-array/
1960
Chapter 304
Smallest subset with sum greater than all other elements - GeeksforGeeks
Given an array of non-negative integers. Our task is to find minimum number of elements
such that their sum should be greater than the sum of rest of the elements of the array.
Examples :
The Brute force approach is to find sum of all the possible subsets and then compare sum
with sum of remaining elements.
The Efficient Approach is to take the largest elements. We sort values in descending
order, then take elements from the largest, until we get strictly more than half of total sum
of the given array.
CPP
1961
Chapter 304. Smallest subset with sum greater than all other elements
Java
1962
Chapter 304. Smallest subset with sum greater than all other elements
class GFG {
// Function to find minimum elements needed
static int minElements(int arr[], int n)
{
// Calculating HALF of array sum
int halfSum = 0;
for (int i = 0; i < n; i++)
halfSum = halfSum + arr[i];
halfSum = halfSum / 2;
// Sort the array in ascending order and
// start traversing array from the ascending
// sort in descending order.
Arrays.sort(arr);
int res = 0, curr_sum = 0;
for (int i = n-1; i >= 0; i--) {
curr_sum += arr[i];
res++;
// Current sum greater than sum
if (curr_sum > halfSum)
return res;
}
return res;
}
// Driver Code
public static void main (String[] args) {
int arr[] = {3, 1, 7, 1};
int n = arr.length;
System.out.println(minElements(arr, n));
}
}
// This code is contributed by Gitanjali
Python3
1963
Chapter 304. Smallest subset with sum greater than all other elements
# calculating HALF of array sum
halfSum = 0
for i in range(n):
halfSum = halfSum + arr[i]
halfSum = int(halfSum / 2)
# sort the array in descending order.
arr.sort(reverse = True)
res = 0
curr_sum = 0
for i in range(n):
curr_sum += arr[i]
res += 1
# current sum greater than sum
if curr_sum > halfSum:
return res
return res
# driver code
arr = [3, 1, 7, 1]
n = len(arr)
print(minElements(arr, n) )
# This code is cntributed by "Sharad_Bhardwaj".
C#
1964
Chapter 304. Smallest subset with sum greater than all other elements
Output:
Source
https://www.geeksforgeeks.org/smallest-subset-sum-greater-elements/
1965
Chapter 305
Sort 1 to N by swapping
adjacent elements
Here we can swap only A[i] with A[i+1]. So to find whether array can be sorted or not.
Using boolean array B we can sort array for a continuous sequence of 1 for B. At last we
can check, if A is sorted or not.
C++
1966
Chapter 305. Sort 1 to N by swapping adjacent elements
// Return true if array can be
// sorted otherwise false
bool sortedAfterSwap(int A[], bool B[], int n)
{
int i, j;
// Check bool array B and sorts
// elements for continuos sequnce of 1
for (i = 0; i < n - 1; i++) {
if (B[i]) {
j = i;
while (B[j])
j++;
// Sort array A from i to j
sort(A + i, A + 1 + j);
i = j;
}
}
// Check if array is sorted or not
for (i = 0; i < n; i++) {
if (A[i] != i + 1)
return false;
}
return true;
}
// Driver program to test sortedAfterSwap()
int main()
{
int A[] = { 1, 2, 5, 3, 4, 6 };
bool B[] = { 0, 1, 1, 1, 0 };
int n = sizeof(A) / sizeof(A[0]);
if (sortedAfterSwap(A, B, n))
cout << "A can be sorted\n";
else
cout << "A can not be sorted\n";
return 0;
}
Java
import java.util.Arrays;
1967
Chapter 305. Sort 1 to N by swapping adjacent elements
// Java program to test whether array
// can be sorted by swapping adjacent
// elements using boolean array
class GFG {
// Return true if array can be
// sorted otherwise false
static boolean sortedAfterSwap(int A[],
boolean B[], int n)
{
int i, j;
// Check bool array B and sorts
// elements for continuos sequnce of 1
for (i = 0; i < n - 1; i++) {
if (B[i]) {
j = i;
while (B[j]) {
j++;
}
// Sort array A from i to j
Arrays.sort(A, i, 1 + j);
i = j;
}
}
// Check if array is sorted or not
for (i = 0; i < n; i++) {
if (A[i] != i + 1) {
return false;
}
}
return true;
}
// Driver program to test sortedAfterSwap()
public static void main(String[] args)
{
int A[] = { 1, 2, 5, 3, 4, 6 };
boolean B[] = { false, true, true, true, false };
int n = A.length;
if (sortedAfterSwap(A, B, n)) {
System.out.println("A can be sorted");
}
1968
Chapter 305. Sort 1 to N by swapping adjacent elements
else {
System.out.println("A can not be sorted");
}
}
}
Python3
1969
Chapter 305. Sort 1 to N by swapping adjacent elements
# This code is contributed
# by Nikita Tiwari.
C#
1970
Chapter 305. Sort 1 to N by swapping adjacent elements
int[] A = { 1, 2, 5, 3, 4, 6 };
bool[] B = { false, true, true, true, false };
int n = A.Length;
if (sortedAfterSwap(A, B, n)) {
Console.WriteLine("A can be sorted");
}
else {
Console.WriteLine("A can not be sorted");
}
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to test whether array
// can be sorted by swapping adjacent
// elements using boolean array
// Return true if array can be
// sorted otherwise false
function sortedAfterSwap($A, $B, $n)
{
// Check bool array B and sorts
// elements for continuos sequnce of 1
for ($i = 0; $i < $n - 1; $i++)
{
if ($B[$i])
{
$j = $i;
while ($B[$j])
$j++;
// Sort array A from i to j
sort($A);
$i = $j;
}
}
// Check if array is sorted or not
for ($i = 0; $i < $n; $i++)
{
if ($A[$i] != $i + 1)
1971
Chapter 305. Sort 1 to N by swapping adjacent elements
return false;
}
return true;
}
// Driver Code
$A = array(1, 2, 5, 3, 4, 6);
$B = array(0, 1, 1, 1, 0);
$n = count($A);
if (sortedAfterSwap($A, $B, $n))
echo "A can be sorted\n";
else
echo "A can not be sorted\n";
// This code is contributed by Sam007
?>
Output:
A can be sorted
Alternative Approach
Here we discuss a very intuitive approach which too gives the answer in O(n) time for all
cases. The idea here is that whenever the binary array has 1, we check if that index in array
A has i+1 or not. If it does not contain i+1, we simply swap a[i] with a[i+1].
The reason for this is that the array should have i+1 stored at index i. And if at all the array
is sortable, then the only operation allowed is swapping. Hence, if the required condition is
not satisfied, we simply swap. If the array is sortable, swapping will take us one step closer
to the correct answer. And as expected, if the array is not sortable, then swapping would
lead to just another unsorted version of the same array.
1972
Chapter 305. Sort 1 to N by swapping adjacent elements
Output:
A can be sorted
Source
https://www.geeksforgeeks.org/sort-1-n-swapping-adjacent-elements/
1973
Chapter 306
Sort 3 Integers without using if condition or using only max() function - GeeksforGeeks
Given three integers, print them in sorted order without using if condition.
Examples :
Input : a = 3, b = 2, c = 9
Output : 2 3 9
Input : a = 4, b = 1, c = 9
Output : 1 4 9
Approach :
1. Find the maximum of a, b, c using max() function.
3. Multiply all integers by –1. Again find Minimum of –a, –b, –c using max() function.
4. Add the Max and Min from above steps and subtract the sum from (a+b+c). It gives
us middle element.
It works for negative numbers also.
C++
1974
Chapter 306. Sort 3 Integers without using if condition or using only max() function
Java
1975
Chapter 306. Sort 3 Integers without using if condition or using only max() function
int a = 4, b = 1, c = 9;
printSorted(a, b, c);
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
1976
Chapter 306. Sort 3 Integers without using if condition or using only max() function
int get_mid = (a + b + c) -
(get_max + get_min);
Console.Write(get_min + " " + get_mid
+ " " + get_max);
}
// Driver code
public static void Main()
{
int a = 4, b = 1, c = 9;
printSorted(a, b, c);
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to print three numbers
// in sorted order using max function
function printSorted($a, $b, $c)
{
// Find maximum element
$get_max = max($a, max($b, $c));
// Find minimum element
$get_min = -max(-$a, max(-$b, -$c));
$get_mid = ($a + $b + $c) -
($get_max + $get_min);
echo $get_min , " " , $get_mid, " " , $get_max;
}
// Driver Code
$a = 4;
$b = 1;
$c = 9;
printSorted($a, $b,$c);
// This code is contributed by nitin mittal.
?>
1977
Chapter 306. Sort 3 Integers without using if condition or using only max() function
Output:
1 4 9
Source
https://www.geeksforgeeks.org/sort-3-integers-without-using-condition-using-max-function/
1978
Chapter 307
Sort 3 numbers
1979
Chapter 307. Sort 3 numbers
Java
C#
// C# program to sort
// an array of size 3
using System;
class GFG
{
public static void Main ()
{
int []a = {10, 12, 5};
Array.Sort(a);
for (int i = 0; i < 3; i++)
Console.Write( a[i] + " ");
}
}
// This code is contributed
// by chandan_jnu.
PHP
<?php
1980
Chapter 307. Sort 3 numbers
Output:
5 10 12
How to write our own sort function that does minimum comparison and does
not use extra variables?
The idea is to use insertion sort as insertion sort works best for small arrays.
C++
1981
Chapter 307. Sort 3 numbers
sort3(a);
for (int i = 0; i < 3; i++)
cout << a[i] << " ";
return 0;
}
Java
1982
Chapter 307. Sort 3 numbers
C#
// C# program to sort
// an array of size 3
using System;
class GFG {
static void sort3(int []arr, int []temp)
{
// Insert arr[1]
if (arr[1] < arr[0])
{
temp[0] = arr[0];
arr[0] = arr[1];
arr[1] = temp[0];
}
// Insert arr[2]
if (arr[2] < arr[1])
{
temp[0] = arr[1];
arr[1] = arr[2];
arr[2] = temp[0];
if (arr[1] < arr[0])
{
temp[0] = arr[0];
arr[0] = arr[1];
arr[1] = temp[0];
}
}
}
// Driver Code
1983
Chapter 307. Sort 3 numbers
Output:
5 10 12
Source
https://www.geeksforgeeks.org/sort-3-numbers/
1984
Chapter 308
Sorting any matrix in a way that its rows, columns and main diagonal are in increasing
order is easy. If we consider matrix elements in sequence according to row-major order and
sort the sequence, we get the desired result.
1985
Chapter 308. Sort a Matrix in all way increasing order
Output:
0 1 2
3 4 5
6 8 9
1986
Chapter 308. Sort a Matrix in all way increasing order
Source
https://www.geeksforgeeks.org/sort-matrix-way-increasing-order/
1987
Chapter 309
Input : [3, 4, 1, 2]
Output : [1, 2, 3, 4]
Input : [2, 3, 4, 1]
Output : [1, 2, 3, 4]
We find the point of rotation. Then we rotate array using reversal algorithm.
1988
Chapter 309. Sort a Rotated Sorted Array
Output:
1 2 3 4 5
1. First find the index of minimum element (split index) in the array using binary search
1989
Chapter 309. Sort a Rotated Sorted Array
1990
Chapter 309. Sort a Rotated Sorted Array
}
// Function to print the Array
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
// Driver function
int main()
{
int arr[] = { 1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
restoreSortedArray(arr, n);
printArray(arr, n);
return 0;
}
Output:
1 2 3 4 5
Source
https://www.geeksforgeeks.org/sort-rotated-sorted-array/
1991
Chapter 310
Input : 1 0 0 1 0 1 0 1 1 1 1 1 1 0 0 1 1 0 1 0 0
Output : 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
Input : 1 0 1 0 1 0 1 0
Output : 0 0 0 0 1 1 1 1
This concept is related to partition of quick sort. In quick sort’ partition, after one scan,
the left of array in smallest and right of array is largest of selected pivot element. So this
concept related to quick sort.but it works in O(n) time only.
let’s understand this concept with this code
CPP
1992
Chapter 310. Sort a binary array using one traversal
Java
1993
Chapter 310. Sort a binary array using one traversal
int a[] = { 1, 0, 0, 1, 0, 1, 0, 1, 1, 1,
1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0 };
int n = a.length;
sortBinaryArray(a, n);
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
}
Python3
C#
1994
Chapter 310. Sort a binary array using one traversal
using System;
class GFG {
static void sortBinaryArray(int[] a,
int n)
{
int j = -1;
for (int i = 0; i < n; i++)
{
// if number is smaller than
// 1 then swap it with j-th
// number
if (a[i] < 1) {
j++;
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
/* Driver program to test above
function */
public static void Main()
{
int[] a = { 1, 0, 0, 1, 0, 1, 0,
1, 1, 1, 1, 1, 1, 0,
0, 1, 1, 0, 1, 0, 0 };
int n = a.Length;
sortBinaryArray(a, n);
for (int i = 0; i < n; i++)
Console.Write(a[i] + " ");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Code for Sort a binary
// array using one traversal
1995
Chapter 310. Sort a binary array using one traversal
Output :
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
Source
https://www.geeksforgeeks.org/sort-binary-array-using-one-traversal/
1996
Chapter 311
1997
Chapter 311. Sort a linked list of 0s, 1s and 2s
1998
Chapter 311. Sort a linked list of 0s, 1s and 2s
Java
1999
Chapter 311. Sort a linked list of 0s, 1s and 2s
void sortList()
{
// initialise count of 0 1 and 2 as 0
int count[] = {0, 0, 0};
Node ptr = head;
/* count total number of '0', '1' and '2'
* count[0] will store total number of '0's
* count[1] will store total number of '1's
* count[2] will store total number of '2's */
while (ptr != null)
{
count[ptr.data]++;
ptr = ptr.next;
}
int i = 0;
ptr = head;
/* Let say count[0] = n1, count[1] = n2 and count[2] = n3
* now start traversing list from head node,
* 1) fill the list with 0, till n1 > 0
* 2) fill the list with 1, till n2 > 0
* 3) fill the list with 2, till n3 > 0 */
while (ptr != null)
{
if (count[i] == 0)
i++;
else
{
ptr.data= i;
--count[i];
ptr = ptr.next;
}
}
}
/* Utility functions */
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
2000
Chapter 311. Sort a linked list of 0s, 1s and 2s
Python
2001
Chapter 311. Sort a linked list of 0s, 1s and 2s
2002
Chapter 311. Sort a linked list of 0s, 1s and 2s
# 1 & 2: Allocate the Node &
# Put in the data
new_node = self.Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# Function to print linked list
def printList(self):
temp = self.head
while temp != None:
print str(temp.data),
temp = temp.next
print ''
# Drier program to test above functions
llist = LinkedList()
llist.push(0)
llist.push(1)
llist.push(0)
llist.push(2)
llist.push(1)
llist.push(1)
llist.push(2)
llist.push(1)
llist.push(2)
print "Linked List before sorting"
llist.printList()
llist.sortList()
print "Linked List after sorting"
llist.printList()
# This code is contributed by BHAVYA JAIN
Output:
2003
Chapter 311. Sort a linked list of 0s, 1s and 2s
Source
https://www.geeksforgeeks.org/sort-a-linked-list-of-0s-1s-or-2s/
2004
Chapter 312
Input : 2->1->2->1->1->2->0->1->0
Output : 0->0->1->1->1->1->2->2->2
Input : 2->1->0
Output : 0->1->2
We have discussed a solution in below post that works by changing data of nodes.
Sort a linked list of 0s, 1s and 2s
The above solution does not work when these values have associated data with them. For
example, these three represent three colors and different types of objects associated with
the colors and we want to sort objects (connected with a linked list) based on colors.
In this post, a new solution is discussed that works by changing links.
Iterate through the linked list. Maintain 3 pointers named zero, one and two to point to
current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed
node, we attach it to the end of its corresponding list. Finally we link all three lists. To
avoid many null checks, we use three dummy pointers zeroD, oneD and twoD that work as
dummy headers of three lists.
2005
Chapter 312. Sort a linked list of 0s, 1s and 2s by changing links
/* Link list node */
struct Node {
int data;
struct Node* next;
};
Node* newNode(int data);
// Sort a linked list of 0s, 1s and 2s
// by changing pointers.
Node* sortList(Node* head)
{
if (!head || !(head->next))
return head;
// Create three dummy nodes to point to
// beginning of three linked lists. These
// dummy nodes are created to avoid many
// null checks.
Node* zeroD = newNode(0);
Node* oneD = newNode(0);
Node* twoD = newNode(0);
// Initialize current pointers for three
// lists and whole list.
Node* zero = zeroD, *one = oneD, *two = twoD;
// Traverse list
Node* curr = head;
while (curr) {
if (curr->data == 0) {
zero->next = curr;
zero = zero->next;
curr = curr->next;
} else if (curr->data == 1) {
one->next = curr;
one = one->next;
curr = curr->next;
} else {
two->next = curr;
two = two->next;
curr = curr->next;
}
}
// Attach three lists
zero->next = (oneD->next) ? (oneD->next) : (twoD->next);
2006
Chapter 312. Sort a linked list of 0s, 1s and 2s by changing links
one->next = twoD->next;
two->next = NULL;
// Updated head
head = zeroD->next;
// Delete dummy nodes
delete zeroD;
delete oneD;
delete twoD;
return head;
}
// function to create and return a node
Node* newNode(int data)
{
// allocating space
Node* newNode = new Node;
// inserting the required data
newNode->data = data;
newNode->next = NULL;
}
/* Function to print linked list */
void printList(struct Node* node)
{
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
/* Drier program to test above function*/
int main(void)
{
// Creating the list 1->2->4->5
Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(0);
head->next->next->next = newNode(1);
printf("Linked List Before Sorting\n");
printList(head);
head = sortList(head);
2007
Chapter 312. Sort a linked list of 0s, 1s and 2s by changing links
printf("Linked List After Sorting\n");
printList(head);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/sort-linked-list-0s-1s-2s-changing-links/
2008
Chapter 313
Sort a linked list that is sorted alternating ascending and descending orders? - Geeks-
forGeeks
Given a Linked List. The Linked List is in alternating ascending and descending orders.
Sort the list efficiently.
Example:
A Simple Solution is to use Merge Sort for linked List. This solution takes O(n Log n)
time.
An Efficient Solution works in O(n) time. Below are all steps.
1. Separate two lists.
2. Reverse the one with descending order
3. Merge both lists.
Below are C++ and Java implementations of above algorithm.
C++
2009
Chapter 313. Sort a linked list that is sorted alternating ascending and descending orders?
struct Node
{
int data;
struct Node *next;
};
Node *mergelist(Node *head1, Node *head2);
void splitList(Node *head, Node **Ahead, Node **Dhead);
void reverselist(Node *&head);
// This is the main function that sorts the
// linked list
void sort(Node **head)
{
// Split the list into lists
Node *Ahead, *Dhead;
splitList(*head, &Ahead, &Dhead);
// Reverse the descending linked list
reverselist(Dhead);
// Merge the two linked lists
*head = mergelist(Ahead, Dhead);
}
// A utility function to create a new node
Node* newNode(int key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
// A utility function to reverse a linked list
void reverselist(Node *&head)
{
Node* prev = NULL, *curr = head, *next;
while (curr)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
}
2010
Chapter 313. Sort a linked list that is sorted alternating ascending and descending orders?
2011
Chapter 313. Sort a linked list that is sorted alternating ascending and descending orders?
Java
2012
Chapter 313. Sort a linked list that is sorted alternating ascending and descending orders?
2013
Chapter 313. Sort a linked list that is sorted alternating ascending and descending orders?
current.next = prev;
prev = current;
current = next;
}
Dhead = prev;
return Dhead;
}
/* Function to print linked list */
void printList()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
// A utility function to merge two sorted linked lists
Node mergeList(Node head1, Node head2)
{
// Base cases
if (head1 == null) return head2;
if (head2 == null) return head1;
Node temp = null;
if (head1.data < head2.data)
{
temp = head1;
head1.next = mergeList(head1.next, head2);
}
else
{
temp = head2;
head2.next = mergeList(head1, head2.next);
}
return temp;
}
// This function alternatively splits a linked list with head
// as head into two:
// For example, 10->20->30->15->40->7 is splitted into 10->30->40
// and 20->15->7
// "Ahead" is reference to head of ascending linked list
// "Dhead" is reference to head of descending linked list
void splitList(Node Ahead, Node Dhead)
2014
Chapter 313. Sort a linked list that is sorted alternating ascending and descending orders?
{
Node ascn = Ahead;
Node dscn = Dhead;
Node curr = head;
// Link alternate nodes
while (curr != null)
{
// Link alternate nodes in ascending order
ascn.next = curr;
ascn = ascn.next;
curr = curr.next;
if (curr != null)
{
dscn.next = curr;
dscn = dscn.next;
curr = curr.next;
}
}
ascn.next = null;
dscn.next = null;
}
/* Drier program to test above functions */
public static void main(String args[])
{
LinkedList llist = new LinkedList();
llist.head = llist.newNode(10);
llist.head.next = llist.newNode(40);
llist.head.next.next = llist.newNode(53);
llist.head.next.next.next = llist.newNode(30);
llist.head.next.next.next.next = llist.newNode(67);
llist.head.next.next.next.next.next = llist.newNode(12);
llist.head.next.next.next.next.next.next = llist.newNode(89);
System.out.println("Given linked list");
llist.printList();
llist.sort();
System.out.println("Sorted linked list");
llist.printList();
}
} /* This code is contributed by Rajat Mishra */
2015
Chapter 313. Sort a linked list that is sorted alternating ascending and descending orders?
Python
2016
Chapter 313. Sort a linked list that is sorted alternating ascending and descending orders?
2017
Chapter 313. Sort a linked list that is sorted alternating ascending and descending orders?
llist.head.next.next = llist.newNode(53)
llist.head.next.next.next = llist.newNode(30)
llist.head.next.next.next.next = llist.newNode(67)
llist.head.next.next.next.next.next = llist.newNode(12)
llist.head.next.next.next.next.next.next = llist.newNode(89)
print 'Given linked list'
llist.printList()
llist.sort()
print 'Sorted linked list'
llist.printList()
# This code is contributed by BHAVYA JAIN
Output:
Source
https://www.geeksforgeeks.org/how-to-sort-a-linked-list-that-is-sorted-alternating-ascending-and-descending-order
2018
Chapter 314
We can use Insertion Sort to sort the elements efficiently. Following is the C code for
standard Insertion Sort.
2019
Chapter 314. Sort a nearly sorted (or K sorted) array
The inner loop will run at most k times. To move every element to its correct place, at most
k elements need to be moved. So overall complexity will be O(nk)
We can sort such arrays more efficiently with the help of Heap data structure.
Following is the detailed process that uses Heap.
1) Create a Min Heap of size k+1 with first k+1 elements. This will take O(k) time (See
this GFact)
2) One by one remove min element from heap, put it in result array, and add a new element
to heap from remaining elements.
Removing an element and adding a new element to min heap will take Logk time. So overall
complexity will be O(k) + O((n-k)*logK)
C++
2020
Chapter 314. Sort a nearly sorted (or K sorted) array
arr[index++] = pq.top();
pq.pop();
}
}
// A utility function to print array elements
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver program to test above functions
int main()
{
int k = 3;
int arr[] = { 2, 6, 3, 12, 56, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
sortK(arr, n, k);
cout << "Following is sorted arrayn";
printArray(arr, n);
return 0;
}
#include<iostream>
using namespace std;
// Prototype of a utility function to swap two integers
void swap(int *x, int *y);
// A class for Min Heap
class MinHeap
{
int *harr; // pointer to array of elements in heap
int heap_size; // size of min heap
public:
// Constructor
MinHeap(int a[], int size);
// to heapify a subtree with root at given index
void MinHeapify(int );
// to get index of left child of node at index i
2021
Chapter 314. Sort a nearly sorted (or K sorted) array
2022
Chapter 314. Sort a nearly sorted (or K sorted) array
while (i >= 0)
{
MinHeapify(i);
i--;
}
}
// Method to remove minimum element (or root) from min heap
int MinHeap::extractMin()
{
int root = harr[0];
if (heap_size > 1)
{
harr[0] = harr[heap_size-1];
heap_size--;
MinHeapify(0);
}
return root;
}
// Method to change root with given value x, and return the old root
int MinHeap::replaceMin(int x)
{
int root = harr[0];
harr[0] = x;
if (root < x)
MinHeapify(0);
return root;
}
// A recursive method to heapify a subtree with root at given index
// This method assumes that the subtrees are already heapified
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i])
smallest = l;
if (r < heap_size && harr[r] < harr[smallest])
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
2023
Chapter 314. Sort a nearly sorted (or K sorted) array
Output:
The Min Heap based method takes O(nLogk) time and uses O(k) auxiliary space.
We can also use a Balanced Binary Search Tree instead of Heap to store K+1 elements.
The insertand deleteoperations on Balanced BST also take O(Logk) time. So Balanced BST
based method will also take O(nLogk) time, but the Heap bassed method seems to be more
efficient as the minimum element will always be at root. Also, Heap doesn’t need extra
space for left and right pointers.
Source
https://www.geeksforgeeks.org/nearly-sorted-algorithm/
2024
Chapter 315
A simple solution is to sort the array using any standard sorting algorithm. The time
complexity of this solution is O(n Log n)
A better solution is to use priority queue (or heap data structure).
We have discussed a simple implementation in Sort a nearly sorted (or K sorted) array. In
this post, an STL based implementation is done.
2025
Chapter 315. Sort a nearly sorted array using STL
2026
Chapter 315. Sort a nearly sorted array using STL
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/sort-a-nearly-sorted-array-using-stl/
2027
Chapter 316
Input : [3, 5, 1, 4, 2, 8]
Output : [1, 2, 3, 4, 5, 8]
2028
Chapter 316. Sort a stack using a temporary stack
2029
Chapter 316. Sort a stack using a temporary stack
C++
// C++ program to sort a stack using an
// auxiliary stack.
#include <bits/stdc++.h>
using namespace std;
// This function return the sorted stack
stack<int> sortStack(stack<int> &input)
{
stack<int> tmpStack;
while (!input.empty())
{
// pop out the first element
int tmp = input.top();
input.pop();
// while temporary stack is not empty and top
// of stack is greater than temp
while (!tmpStack.empty() && tmpStack.top() > tmp)
{
// pop from temporary stack and push
// it to the input stack
input.push(tmpStack.top());
tmpStack.pop();
}
// push temp in tempory of stack
tmpStack.push(tmp);
}
return tmpStack;
}
2030
Chapter 316. Sort a stack using a temporary stack
// main function
int main()
{
stack<int> input;
input.push(34);
input.push(3);
input.push(31);
input.push(98);
input.push(92);
input.push(23);
// This is the temporary stack
stack<int> tmpStack = sortStack(input);
cout << "Sorted numbers are:\n";
while (!tmpStack.empty())
{
cout << tmpStack.top()<< " ";
tmpStack.pop();
}
}
Java
2031
Chapter 316. Sort a stack using a temporary stack
input.push(tmpStack.pop());
}
// push temp in tempory of stack
tmpStack.push(tmp);
}
return tmpStack;
}
// Driver Code
public static void main(String args[])
{
Stack<Integer> input = new Stack<Integer>();
input.add(34);
input.add(3);
input.add(31);
input.add(98);
input.add(92);
input.add(23);
// This is the temporary stack
Stack<Integer> tmpStack=sortstack(input);
System.out.println("Sorted numbers are:");
while (!tmpStack.empty())
{
System.out.print(tmpStack.pop()+" ");
}
}
}
// This code is contributed by Danish Kaleem
Python3
2032
Chapter 316. Sort a stack using a temporary stack
2033
Chapter 316. Sort a stack using a temporary stack
Output:
Microsoft
Improved By : programmer2k17, Prasad_Kshirsagar
Source
https://www.geeksforgeeks.org/sort-stack-using-temporary-stack/
2034
Chapter 317
Sort all even numbers in ascending order and then sort all odd numbers in descending order
- GeeksforGeeks
Given an array of integers (both odd and even), sort them in such a way that the first part
of the array contains odd numbers sorted in descending order, rest portion contains even
numbers sorted in ascending order.
Examples:
Asked in : Microsoft
Method 1 (Using Partition)
1. Partition the input array such that all odd elements are moved to left and all even
elements on right. This step takes O(n).
2. Once the array is partitioned, sort left and right parts individually. This step takes
O(n Log n).
2035
Chapter 317. Sort all even numbers in ascending order and then sort all odd numbers in
descending order
2036
Chapter 317. Sort all even numbers in ascending order and then sort all odd numbers in
descending order
{
int arr[] = {1, 3, 2, 7, 5, 4};
int n = sizeof(arr)/sizeof(int);
twoWaySort(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Java
2037
Chapter 317. Sort all even numbers in ascending order and then sort all odd numbers in
descending order
Python
2038
Chapter 317. Sort all even numbers in ascending order and then sort all odd numbers in
descending order
2039
Chapter 317. Sort all even numbers in ascending order and then sort all odd numbers in
descending order
Output:
7 5 3 1 2 4
C++
2040
Chapter 317. Sort all even numbers in ascending order and then sort all odd numbers in
descending order
}
// Driver code
int main()
{
int arr[] = {1, 3, 2, 7, 5, 4};
int n = sizeof(arr)/sizeof(int);
twoWaySort(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Java
2041
Chapter 317. Sort all even numbers in ascending order and then sort all odd numbers in
descending order
System.out.println(Arrays.toString(arr));
}
}
Python3
C#
2042
Chapter 317. Sort all even numbers in ascending order and then sort all odd numbers in
descending order
Output:
7 5 3 1 2 4
2043
Chapter 317. Sort all even numbers in ascending order and then sort all odd numbers in
descending order
This method may not work when input array contains negative numbers. However, there is
a way to handle this. We count the positive odd integers in the input array then sort again.
Readers may refer this for implementation.
Thanks to Amandeep Singh for suggesting this solution.
Improved By : Smitha Dinesh Semwal, jaysiyaram
Source
https://www.geeksforgeeks.org/sort-even-numbers-ascending-order-sort-odd-numbers-descending-order/
2044
Chapter 318
Sort an almost sorted array where only two elements are swapped - GeeksforGeeks
Given an almost sorted array where only two elements are swapped, how to sort the array
efficiently?
Examples :
Expected time complexity is O(n) and only one swap operation to fix the array.
The idea is to traverse from rightmost side and find the first out of order element (element
which is smaller than previous element). Once first element is found, find the other our of
order element by traversing the array toward left side.
Below is implementation of above idea.
C++
2045
Chapter 318. Sort an almost sorted array where only two elements are swapped
2046
Chapter 318. Sort an almost sorted array where only two elements are swapped
Java
2047
Chapter 318. Sort an almost sorted array where only two elements are swapped
Output :
Given array is
10 30 20 40 50 60 70
Sorted array is
10 20 30 40 50 60 70
The above program works in O(n) time and swaps only one element.
Improved By : vt_m
Source
https://www.geeksforgeeks.org/sort-an-almost-sorted-array-where-only-two-elements-are-swapped/
2048
Chapter 319
Sort an array according to absolute difference with a given value ”using constant extra space”
- GeeksforGeeks
Given an array of n distinct elements and a number x, arrange array elements according to
the absolute difference with x, i. e., element having minimum difference comes first and so
on, using constant extra space.
Note : If two or more elements are at equal distance arrange them in same sequence as in
the given array.
Examples:
2049
Chapter 319. Sort an array according to absolute difference with a given value “using
constant extra space”
x = 6
Output : arr[] = {5, 4, 3, 2, 1}
The above problem has already been explained in a previous post here. It takes O(n log n)
time and O(n) extra space. The below solution though has a relatively bad time complexity
i.e O(n^2) but it does the work without using any additional space or memory.
The solution is a based on Insertion Sort. For every i (1<= i < n) we compare the absolute
value of the difference of arr[i] with the given number x (Let this be ’diff’ ). We then compare
this difference with the difference of abs(arr[j]-x) where 0<= j < i (Let this if abdiff). If diff
is greater than abdiff, we shift the values in the array to accommodate arr[i] in it’s correct
position.
2050
Chapter 319. Sort an array according to absolute difference with a given value “using
constant extra space”
Output:
5 9 10 3 2
Source
https://www.geeksforgeeks.org/sort-array-according-absolute-difference-given-value-using-constant-extra-space/
2051
Chapter 320
2052
Chapter 320. Sort an array according to absolute difference with given value
The idea is to use a self balancing binary search tree. We traverse input array and for every
element, we find its difference with x and store the difference as key and element as value in
self balancing binary search tree. Finally we traverse the tree and print its inorder traversal
which is required output.
C++ Implementation :
In C++, self-balancing-bianry-search-tree is implemented by set, map and multimap. We
can’t use set here as we have key value pairs (not only keys). We also can’t directly use map
also as a single key can belong to multiple values and map allows a single value for a key.
So we use multimap which stores key value pairs and can have multiple values for a key.
1. Store the values in the multimap with the difference with X as key.
2. In multiimap, the values will be already in sorted order according to key i.e. difference
with X because it implements self-balancing-bianry-search-tree internally.
3. Update all the values of array with the values of map so that array has the required
output.
2053
Chapter 320. Sort an array according to absolute difference with given value
int main()
{
int arr[] = {10, 5, 3, 9 ,2};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 7;
rearrange(arr, n, x);
printArray(arr, n);
return 0;
}
Output:
5 9 10 3 2
Source
https://www.geeksforgeeks.org/sort-an-array-according-to-absolute-difference-with-given-value/
2054
Chapter 321
2055
Chapter 321. Sort an array according to count of set bits
Explanation:
3 - 0011
5 - 0101
6 - 0110
1 - 0001
2 - 0010
4 - 0100
hence the non-increasing sorted order is
{3, 5, 6}, {1, 2, 4}
Method 1: Simple
1. Create an auxiliary array and store the set-bit counts of all integers in the aux array
Before sort:
int arr[] = {1, 2, 3, 4, 5, 6};
int aux[] = {1, 1, 2, 1, 2, 2}
After sort:
arr = {3, 5, 6, 1, 2, 4}
aux = {2, 2, 2, 1, 1, 1}
Implementation:
C++
2056
Chapter 321. Sort an array according to count of set bits
2057
Chapter 321. Sort an array according to count of set bits
// Driver Code
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
sortBySetBitCount(arr, n);
printArr(arr, n);
return 0;
}
Java
2058
Chapter 321. Sort an array according to count of set bits
2059
Chapter 321. Sort an array according to count of set bits
// Driver Code
public static void main (String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6};
int n = arr.length;
sortBySetBitCount(arr, n);
printArr(arr, n);
}
}
// This code is contributed by anuj_67.
Output:
3 5 6 1 2 4
2060
Chapter 321. Sort an array according to count of set bits
// custom comparator of std::sort
int cmp(int a,int b)
{
int count1 = countBits(a);
int count2 = countBits(b);
// this takes care of the stability of
// sorting algorithm too
if (count1 <= count2)
return false;
return true;
}
// Function to sort according to bit count using
// std::sort
void sortBySetBitCount(int arr[], int n)
{
stable_sort(arr, arr+n, cmp);
}
// Utility function to print an array
void printArr(int arr[], int n)
{
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}
// Driver Code
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
sortBySetBitCount(arr, n);
printArr(arr, n);
return 0;
}
Output:
3 5 6 1 2 4
2061
Chapter 321. Sort an array according to count of set bits
This problem can be solved in O(n) time. The idea is similar to counting sort.
Note: There can be minimum 1 set-bit and only a maximum of 31set-bits in any integer.
Steps (assuming that an integer takes 32 bits):
1. Create a vector “count” of size 32. Each cell of count i.e., count[i] is another vector
that stores all the elements whose set-bit-count is i
C++
2062
Chapter 321. Sort an array according to count of set bits
}
// Function to sort according to bit count
// This function assumes that there are 32
// bits in an integer.
void sortBySetBitCount(int arr[],int n)
{
vector<vector<int> > count(32);
int setbitcount = 0;
for (int i=0; i<n; i++)
{
setbitcount = countBits(arr[i]);
count[setbitcount].push_back(arr[i]);
}
int j = 0; // Used as an index in final sorted array
// Traverse through all bit counts (Note that we
// sort array in decreasing order)
for (int i=31; i>=0; i--)
{
vector<int> v1 = count[i];
for (int i=0; i<v1.size(); i++)
arr[j++] = v1[i];
}
}
// Utility function to print an array
void printArr(int arr[], int n)
{
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}
// Driver Code
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
sortBySetBitCount(arr, n);
printArr(arr, n);
return 0;
}
Output:
3 5 6 1 2 4
2063
Chapter 321. Sort an array according to count of set bits
Source
https://www.geeksforgeeks.org/sort-array-according-count-set-bits/
2064
Chapter 322
The code should handle all cases like number of elements in A2[] may be more or less
compared to A1[]. A2[] may have some elements which may not be there in A1[] and vice
versa is also possible.
Source: Amazon Interview Set 110 (On-Campus)
Method 1 (Using Sorting and Binary Search)
Let size of A1[] be m and size of A2[] be n.
1) Create a temporary array temp of size m and copy contents of A1[] to it.
2) Create another array visited[] and initialize all entries in it as false. visited[] is used to
mark those elements in temp[] which are copied to A1[].
3) Sort temp[]
4) Initialize the output index ind as 0.
5) Do following for every element of A2[i] in A2[]
…..a) Binary search for all occurrences of A2[i] in temp[], if present then copy all occurrences
to A1[ind] and increment ind. Also mark the copied elements visited[]
6) Copy all unvisited elements from temp[] to A1[].
Time complexity: The steps 1 and 2 require O(m) time. Step 3 requires O(mLogm) time.
Step 5 requires O(nLogm) time. Therefore overall time complexity is O(mLogm + nLogm).
2065
Chapter 322. Sort an array according to the order defined by another array
Thanks to vivekfor suggesting this method. Following is the implementation of above algo-
rithm.
C++
2066
Chapter 322. Sort an array according to the order defined by another array
Java
2067
Chapter 322. Sort an array according to the order defined by another array
class GFG {
/* A Binary Search based function to find
index of FIRST occurrence of x in arr[].
If x is not present, then it returns -1 */
static int first(int arr[], int low, int high,
int x, int n)
{
if (high >= low)
{
/* (low + high)/2; */
int mid = low + (high-low)/2;
if ((mid == 0 || x > arr[mid-1]) &&
arr[mid] == x)
return mid;
if (x > arr[mid])
return first(arr, (mid + 1), high,
x, n);
return first(arr, low, (mid -1), x, n);
}
return -1;
}
// Sort A1[0..m-1] according to the order
// defined by A2[0..n-1].
static void sortAccording(int A1[], int A2[], int m,
int n)
{
// The temp array is used to store a copy
// of A1[] and visited[] is used to mark the
// visited elements in temp[].
int temp[] = new int[m], visited[] = new int[m];
for (int i = 0; i < m; i++)
{
temp[i] = A1[i];
visited[i] = 0;
}
// Sort elements in temp
Arrays.sort(temp);
// for index of output which is sorted A1[]
int ind = 0;
// Consider all elements of A2[], find them
// in temp[] and copy to A1[] in order.
for (int i = 0; i < n; i++)
2068
Chapter 322. Sort an array according to the order defined by another array
{
// Find index of the first occurrence
// of A2[i] in temp
int f = first(temp, 0, m-1, A2[i], m);
// If not present, no need to proceed
if (f == -1) continue;
// Copy all occurrences of A2[i] to A1[]
for (int j = f; (j < m && temp[j] == A2[i]);
j++)
{
A1[ind++] = temp[j];
visited[j] = 1;
}
}
// Now copy all items of temp[] which are
// not present in A2[]
for (int i = 0; i < m; i++)
if (visited[i] == 0)
A1[ind++] = temp[i];
}
// Utility function to print an array
static void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver program to test above function.
public static void main(String args[])
{
int A1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8};
int A2[] = {2, 1, 8, 3};
int m = A1.length;
int n = A2.length;
System.out.println("Sorted array is ");
sortAccording(A1, A2, m, n);
printArray(A1, m);
}
}
/*This code is contributed by Nikita Tiwari.*/
2069
Chapter 322. Sort an array according to the order defined by another array
Python3
2070
Chapter 322. Sort an array according to the order defined by another array
# If not present, no need to proceed
if (f == -1) :
continue
# Copy all occurrences of A2[i] to A1[]
j = f
while (j<m and temp[j]==A2[i]) :
A1[ind] = temp[j];
ind=ind+1
visited[j] = 1
j = j + 1
# Now copy all items of temp[] which are
# not present in A2[]
for i in range(0, m) :
if (visited[i] == 0) :
A1[ind] = temp[i]
ind = ind + 1
# Utility function to print an array
def printArray(arr, n) :
for i in range(0, n) :
print(arr[i], end = " ")
print("")
# Driver program to test above function.
A1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]
A2 = [2, 1, 8, 3]
m = len(A1)
n = len(A2)
print("Sorted array is ")
sortAccording(A1, A2, m, n)
printArray(A1, m)
# This code is contributed by Nikita Tiwari.
C#
2071
Chapter 322. Sort an array according to the order defined by another array
2072
Chapter 322. Sort an array according to the order defined by another array
// order.
for (int i = 0; i < n; i++)
{
// Find index of the first occurrence
// of A2[i] in temp
int f = first(temp, 0, m-1, A2[i], m);
// If not present, no need to proceed
if (f == -1) continue;
// Copy all occurrences of A2[i] to A1[]
for (int j = f; (j < m &&
temp[j] == A2[i]); j++)
{
A1[ind++] = temp[j];
visited[j] = 1;
}
}
// Now copy all items of temp[] which are
// not present in A2[]
for (int i = 0; i < m; i++)
if (visited[i] == 0)
A1[ind++] = temp[i];
}
// Utility function to print an array
static void printArray(int []arr, int n)
{
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver program to test above function.
public static void Main()
{
int []A1 = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8};
int []A2 = {2, 1, 8, 3};
int m = A1.Length;
int n = A2.Length;
Console.WriteLine("Sorted array is ");
sortAccording(A1, A2, m, n);
printArray(A1, m);
}
}
2073
Chapter 322. Sort an array according to the order defined by another array
Output:
Sorted array is
2 2 1 1 8 8 3 5 6 7 9
2074
Chapter 322. Sort an array according to the order defined by another array
2075
Chapter 322. Sort an array according to the order defined by another array
A2[1] = 1;
A2[2] = 8;
A2[3] = 3;
A2[4] = 4;
int size1 = sizeof(A1)/sizeof(A1[0]);
sortA1ByA2(A1, size1);
printf("Sorted Array is ");
int i;
for (i=0; i<size1; i++)
printf("%d ", A1[i]);
return 0;
}
Output:
Sorted Array is 2 2 1 1 8 8 3 5 5 5 6 6 7 7 7 9 9
This method is based on comments by readers (Xinuo Chen, Pranay Doshi and javakurious)
and compiled by Anurag Singh.
This article is compiled by Piyush. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : nitin mittal, Suryaveer Singh
Source
https://www.geeksforgeeks.org/sort-array-according-order-defined-another-array/
2076
Chapter 323
Asked in : Adobe
Method 1 (Simple) :
1- Apply the given equation on all the elements. O(n)
2- Sort the modified array. O(n Log n)
Time complexity of O(n log n)
Method 2(Efficient): Parabolic Property
The equation given is parabolic. So the result of applying it to a sorted array will result
in an array that will have a maximum/minimum with the sub-arrays to its left and right
sorted.
In the above example, maximum is 0 and the sub array to its left {-4, -1} is sorted in
ascending order and the sub-array to its right {-1, -4, -9} is sorted in descending order.
All we need to do is merge these sorted arrays which is linear in time.
2077
Chapter 323. Sort an array after applying the given equation
Note : The below code assumes that the modified array is first increasing then decreasing.
C++
2078
Chapter 323. Sort an array after applying the given equation
// Merge remaining elements
while (i < index)
new_arr[k++] = arr[i++];
while (j > index)
new_arr[k++] = arr[j--];
new_arr[n-1] = maximum;
// Modify original array
for (int i = 0; i < n ; i++)
arr[i] = new_arr[i];
}
// Driver code
int main()
{
int arr[] = {-21 ,-15, 12, 13, 14 };
int n = sizeof(arr) / sizeof(arr[0]);
int A = -6, B =-7, C = 2;
sortArray(arr, n, A, B, C);
cout << "Array after sorting is : n";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Java
2079
Chapter 323. Sort an array after applying the given equation
2080
Chapter 323. Sort an array after applying the given equation
}
}
/* This code is contributed by Harsh Agarwal */
Output:
Source
https://www.geeksforgeeks.org/sort-array-applying-given-equation/
2081
Chapter 324
2082
Chapter 324. Sort an array containing two types of elements
Java
2083
Chapter 324. Sort an array containing two types of elements
arr[type1] = arr[type0]-arr[type1];
arr[type0] = arr[type0]-arr[type1];
type1--;
} else {
type0++;
}
}
}
// Driver program
public static void main(String[] args) {
int arr[] = { 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1 };
segregate0and1(arr, arr.length);
for (int a : arr)
System.out.print(a+" ");
}
}
Python3
C#
2084
Chapter 324. Sort an array containing two types of elements
Output:
2085
Chapter 324. Sort an array containing two types of elements
0 0 0 1 1 1 1 1 1 1 1
Improved By : san4net
Source
https://www.geeksforgeeks.org/sort-array-containing-two-types-elements/
2086
Chapter 325
A Simple Solution is to use sorting. First sort the input array, then swap all adjacent
elements.
For example, let the input array be {3, 6, 5, 10, 7, 20}. After sorting, we get {3, 5, 6, 7, 10,
20}. After swapping adjacent elements, we get {5, 3, 7, 6, 20, 10}.
Below are implementations of this simple approach.
C++
2087
Chapter 325. Sort an array in wave form
Java
2088
Chapter 325. Sort an array in wave form
Python
2089
Chapter 325. Sort an array in wave form
# This code is contributed by __Devesh Agrawal__
C#
Output:
2090
Chapter 325. Sort an array in wave form
2 1 10 5 49 23 90
The time complexity of the above solution is O(nLogn) if a O(nLogn) sorting algorithm like
Merge Sort, Heap Sort, .. etc is used.
This can be done in O(n) time by doing a single traversal of given array. The idea is
based on the fact that if we make sure that all even positioned (at index 0, 2, 4, ..) elements
are greater than their adjacent odd elements, we don’t need to worry about odd positioned
element. Following are simple steps.
1) Traverse all even positioned elements of input array, and do following.
….a) If current element is smaller than previous odd element, swap previous and current.
….b) If current element is smaller than next odd element, swap next and current.
Below are implementations of above simple algorithm.
C++
2091
Chapter 325. Sort an array in wave form
Java
2092
Chapter 325. Sort an array in wave form
System.out.print(i+" ");
}
}
/*This code is contributed by Rajat Mishra*/
Python
C#
2093
Chapter 325. Sort an array in wave form
// arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4]....
void sortInWave(int[] arr, int n)
{
// Traverse all even elements
for (int i = 0; i < n; i += 2) {
// If current even element is smaller
// than previous
if (i > 0 && arr[i - 1] > arr[i])
swap(arr, i - 1, i);
// If current even element is smaller
// than next
if (i < n - 1 && arr[i] < arr[i + 1])
swap(arr, i, i + 1);
}
}
// Driver program to test above function
public static void Main()
{
SortWave ob = new SortWave();
int[] arr = { 10, 90, 49, 2, 1, 5, 23 };
int n = arr.Length;
ob.sortInWave(arr, n);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by vt_m.
Output:
90 10 49 1 5 2 23
This article is contributed by Shivam. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/sort-array-wave-form-2/
2094
Chapter 326
Input : {0, 1, 2, 0, 1, 2}
Output : {0, 0, 1, 1, 2, 2}
Input : {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}
Output : {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}
1. Lo := 1; Mid := 1; Hi := N;
2095
Chapter 326. Sort an array of 0s, 1s and 2s
Part way through the process, some red, white and blue elements are known and are in the
“right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:
2096
Chapter 326. Sort an array of 0s, 1s and 2s
// Sort the input array, the array is assumed to
// have values in {0, 1, 2}
void sort012(int a[], int arr_size)
{
int lo = 0;
int hi = arr_size - 1;
int mid = 0;
while (mid <= hi)
{
switch (a[mid])
{
case 0:
swap(&a[lo++], &a[mid++]);
break;
case 1:
mid++;
break;
case 2:
swap(&a[mid], &a[hi--]);
break;
}
}
}
/* UTILITY FUNCTIONS */
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
/* Utility function to print array arr[] */
void printArray(int arr[], int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
printf("%d ", arr[i]);
printf("n");
}
/* driver program to test */
int main()
{
int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
int arr_size = sizeof(arr)/sizeof(arr[0]);
2097
Chapter 326. Sort an array of 0s, 1s and 2s
int i;
sort012(arr, arr_size);
printf("array after segregation ");
printArray(arr, arr_size);
getchar();
return 0;
}
Java
2098
Chapter 326. Sort an array of 0s, 1s and 2s
}
}
}
}
/* Utility function to print array arr[] */
static void printArray(int arr[], int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
System.out.print(arr[i]+" ");
System.out.println("");
}
/*Driver function to check for above functions*/
public static void main (String[] args)
{
int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
int arr_size = arr.length;
sort012(arr, arr_size);
System.out.println("Array after seggregation ");
printArray(arr, arr_size);
}
}
/*This code is contributed by Devesh Agrawal*/
Python
2099
Chapter 326. Sort an array of 0s, 1s and 2s
C#
2100
Chapter 326. Sort an array of 0s, 1s and 2s
{
temp = a[mid];
a[mid] = a[hi];
a[hi] = temp;
hi--;
break;
}
}
}
}
/* Utility function to print array arr[] */
static void printArray(int []arr, int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
Console.Write(arr[i] + " ");
Console.WriteLine("");
}
/*Driver function to check for above functions*/
public static void Main ()
{
int []arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
int arr_size = arr.Length;
sort012(arr, arr_size);
Console.Write("Array after seggregation ");
printArray(arr, arr_size);
}
}
//This code is contributed by Sam007
Output:
2101
Chapter 326. Sort an array of 0s, 1s and 2s
Source
https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/
2102
Chapter 327
Input : {0, 1, 2, 0, 1, 2}
Output : {0, 0, 1, 1, 2, 2}
Input : {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}
Output : {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}
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. We traverse the array two times. Time complexity will be O(n).
CPP
2103
Chapter 327. Sort an array of 0s, 1s and 2s (Simple Counting)
if (arr[i] == 0)
count0++;
if (arr[i] == 1)
count1++;
if (arr[i] == 2)
count2++;
}
// Putting the 0's in the array in starting.
for (int i = 0; i < count0; i++)
arr[i] = 0;
// Putting the 1's in the array after the 0's.
for (int i = count0; i < (count0 + count1); i++)
arr[i] = 1;
// Putting the 2's in the array after the 1's
for (int i = (count0 + count1); i < n; i++)
arr[i] = 2;
return;
}
// Prints the array
void printArray(int* arr, int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
sort012(arr, n);
printArray(arr, n);
return 0;
}
Java
2104
Chapter 327. Sort an array of 0s, 1s and 2s (Simple Counting)
public class GfG{
public static void sort012(int arr[], int n)
{
// Variables to maintain
// the count of 0's,
// 1's and 2's in the array
int count0 = 0, count1 = 0;
int count2 = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
count0++;
if (arr[i] == 1)
count1++;
if (arr[i] == 2)
count2++;
}
// Putting the 0's in the
// array in starting.
for (int i = 0; i < count0; i++)
arr[i] = 0;
// Putting the 1's in the
// array after the 0's.
for (int i = count0; i <
(count0 + count1); i++)
arr[i] = 1;
// Putting the 2's in the
// array after the 1's
for (int i = (count0 + count1);
i < n; i++)
arr[i] = 2;
printArray(arr, n);
}
// Prints the array
public static void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver function
2105
Chapter 327. Sort an array of 0s, 1s and 2s (Simple Counting)
Python3
2106
Chapter 327. Sort an array of 0s, 1s and 2s (Simple Counting)
# Prints the array
def printArray( arr, n):
for i in range(0,n):
print( arr[i] , end=" ")
print()
# Driver code
arr = [ 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 ]
n = len(arr)
sort012(arr, n)
printArray(arr, n)
# This code is contributed by Gitanjali.
C#
// Simple C# program
// to sort an array of 0s
// 1s and 2s.
using System;
public class GfG{
public static void sort012(int []arr, int n)
{
// Variables to maintain
// the count of 0's,
// 1's and 2's in the array
int count0 = 0, count1 = 0;
int count2 = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
count0++;
if (arr[i] == 1)
count1++;
if (arr[i] == 2)
count2++;
}
// Putting the 0's in the
// array in starting.
for (int i = 0; i < count0; i++)
arr[i] = 0;
// Putting the 1's in the
2107
Chapter 327. Sort an array of 0s, 1s and 2s (Simple Counting)
Output:
0 0 0 0 0 1 1 1 1 1 2 2
2108
Chapter 327. Sort an array of 0s, 1s and 2s (Simple Counting)
Source
https://www.geeksforgeeks.org/sort-array-0s-1s-2s-simple-counting/
2109
Chapter 328
2110
Chapter 328. Sort an array of large numbers
// If lengths are same
for (int i=0; i<n1; i++)
{
if (str1[i] < str2[i])
return true;
if (str1[i] > str2[i])
return false;
}
return false;
}
// Function for sort an array of large numbers
// represented as strings
void sortLargeNumbers(string arr[], int n)
{
sort(arr, arr+n, compareNumbers);
}
// Driver code
int main()
{
string arr[] = {"5", "1237637463746732323",
"97987", "12" };
int n = sizeof(arr)/sizeof(arr[0]);
sortLargeNumbers(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Java
2111
Chapter 328. Sort an array of large numbers
Output:
5 12 97987 1237637463746732323
Time complexity : O(k * n Log n) where k is length of the longest number. Here assumption
is that the sort() function uses a O(n Log n) sorting algorithm.
Similar Post :
Sorting Big Integers
Source
https://www.geeksforgeeks.org/sort-array-large-numbers/
2112
Chapter 329
A simple solution is to write our own sort function that compares string lengths to decide
which string should come first. Below is the C++ implementation that uses Insertion Sortto
sort the array.
2113
Chapter 329. Sort an array of strings according to string lengths
I am from GeeksforGeeks
A better solution is to use sort function provided by programming languages like C++,
Java. These functions also allow us to write our own custom comparator. Below is C++
implementation that uses C++ STL Sort function.
#include <bits/stdc++.h>
2114
Chapter 329. Sort an array of strings according to string lengths
I am from GeeksforGeeks
Source
https://www.geeksforgeeks.org/sort-array-strings-according-string-lengths/
2115
Chapter 330
Input : 4 5 6 1 8 2 7 9 3 0
Output :0 1 2 3 4 5 6 7 8 9
Input : 9 8 1 4 0
Output : 0 1 4 8 9
Compile these files using gcc command (gcc client.c -o client and gcc server.c -o server).
Run the program using ./server and ./client (Please note : First you should run server
program which will be waiting for client’s response and then client code).
In this program, client will take the input and send it to server and the server will sort the
array using the bubble sort.
2116
Chapter 330. Sort an array using socket programming in C
{
int sock;
struct sockaddr_in server;
int server_reply[10];
int number[10] = { 5, 4, 3, 8, 9, 1, 2, 0, 6 }, i, temp;
// Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(8880);
// Connect to remote server
if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0) {
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
if (send(sock, &number, 10 * sizeof(int), 0) < 0) {
puts("Send failed");
return 1;
}
// Receive a reply from the server
if (recv(sock, &server_reply, 10 * sizeof(int), 0) < 0) {
puts("recv failed");
return 0;
}
puts("Server reply :\n");
for (i = 0; i < 10; i++) {
printf("%d\n", server_reply[i]);
}
// close the socket
close(sock);
return 0;
}
2117
Chapter 330. Sort an array using socket programming in C
2118
Chapter 330. Sort an array using socket programming in C
return 1;
}
puts("Connection accepted");
// Receive a message from client
while ((read_size = recv(client_sock, &message, 10 * sizeof(int), 0)) > 0) {
bubble_sort(message, 10);
write(client_sock, &message, 10 * sizeof(int));
}
if (read_size == 0) {
puts("Client disconnected");
}
else if (read_size == -1) {
perror("recv failed");
}
return 0;
}
// Function to sort the array
void bubble_sort(int list[], int n)
{
int c, d, t;
for (c = 0; c < (n - 1); c++) {
for (d = 0; d < n - c - 1; d++) {
if (list[d] > list[d + 1]) {
/* Swapping */
t = list[d];
list[d] = list[d + 1];
list[d + 1] = t;
}
}
}
}
0 1 2 3 4 5 6 7 8 9
2119
Chapter 330. Sort an array using socket programming in C
Source
https://www.geeksforgeeks.org/sort-array-using-socket-programming/
2120
Chapter 331
2121
Chapter 331. Sort an array when two halves are sorted
int main()
{
int A[] = { 2, 3, 8, -1, 7, 10 };
int n = sizeof(A) / sizeof(A[0]);
mergeTwoHalf(A, n);
// Print sorted Array
for (int i = 0; i < n; i++)
cout << A[i] << " ";
return 0;
}
Java
C#
2122
Chapter 331. Sort an array when two halves are sorted
class GFG {
static void mergeTwoHalf(int[] A, int n)
{
// Sort the given array using sort STL
Array.Sort(A);
}
// Driver program to test above function
static public void Main()
{
int[] A = {2, 3, 8, -1, 7, 10};
int n = A.Length;
mergeTwoHalf(A, n);
// Print sorted Array
for (int i = 0; i < n; i++)
Console.Write(A[i] + " ");
}
}
// This code is contributed by vt_m .
Output:
-1 2 3 7 8 10
Time Complexity O(nlogn) Sort Given array using quick sort or merge sort
An efficient solution is to use an auxiliary array one half. Now whole process is same as
the Merge Function of Marge sort.
Below is the implementation of above approach :
C++
2123
Chapter 331. Sort an array when two halves are sorted
int temp[n];
// First Find the point where array is divide
// into two half
for (int i = 0; i < n - 1; i++) {
if (A[i] > A[i + 1]) {
half_i = i + 1;
break;
}
}
// If Given array is all-ready sorted
if (half_i == 0)
return;
// Merge two sorted arrays in single sorted array
int i = 0, j = half_i, k = 0;
while (i < half_i && j < n) {
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
}
// Copy the remaining elements of A[i to half_! ]
while (i < half_i)
temp[k++] = A[i++];
// Copy the remaining elements of A[ half_! to n ]
while (j < n)
temp[k++] = A[j++];
for (int i = 0; i < n; i++)
A[i] = temp[i];
}
// Driver program to test above function
int main()
{
int A[] = { 2, 3, 8, -1, 7, 10 };
int n = sizeof(A) / sizeof(A[0]);
mergeTwoHalf(A, n);
// Print sorted Array
for (int i = 0; i < n; i++)
cout << A[i] << " ";
return 0;
}
2124
Chapter 331. Sort an array when two halves are sorted
Java
2125
Chapter 331. Sort an array when two halves are sorted
temp[k++] = A[j++];
for (i = 0; i < n; i++)
A[i] = temp[i];
}
// Driver program to test above function
static public void main(String[] args)
{
int[] A = {2, 3, 8, -1, 7, 10};
int n = A.length;
mergeTwoHalf(A, n);
// Print sorted Array
for (int i = 0; i < n; i++)
System.out.print(A[i] + " ");
}
}
// This code is contributed by vt_m .
C#
2126
Chapter 331. Sort an array when two halves are sorted
Output:
-1 2 3 7 8 10
2127
Chapter 331. Sort an array when two halves are sorted
Reference : https://www.careercup.com/question?id=8412257
Improved By : vt_m
Source
https://www.geeksforgeeks.org/sort-array-two-halves-sorted/
2128
Chapter 332
Native approach :
Sort this array with the use of any type of sorting method. it takes O(nlogn) minimum
time.
Efficient approach :
Replace every element with it’s position. it takes O(n) efficient time and give you the sorted
array. Let’s understand this approach with the code below.
C++
2129
Chapter 332. Sort an array which contain 1 to n values
Java
2130
Chapter 332. Sort an array which contain 1 to n values
C#
2131
Chapter 332. Sort an array which contain 1 to n values
}
// This code is contributed by
// Manish Shaw (manishshaw1)
PHP
<?php
// Efficient PHP program to sort an
// array of numbers in range from 1 to n.
// function for sort array
function sortit(&$arr, $n)
{
for ($i = 0; $i < $n; $i++)
{
$arr[$i]=$i+1;
}
}
// Driver code
$arr = array(10, 7, 9, 2, 8,
3, 5, 4, 6, 1);
$n = count($arr);
// for sort an array
sortit($arr, $n);
// for print all the
// element in sorted way
for ($i = 0; $i < $n; $i++)
echo $arr[$i]." ";
//This code is contributed by Manish Shaw
//(manishshaw1)
?>
Output :
1 2 3 4 5 6 7 8 9 10
2132
Chapter 332. Sort an array which contain 1 to n values
Source
https://www.geeksforgeeks.org/sort-array-contain-1-n-values/
2133
Chapter 333
Sort an array with swapping only with a special element is allowed - GeeksforGeeks
Given an array of length n + 1, containing elements 1 through n and a space, Requires the
use of a given swap (index i, index j) function to sort the array, You can only swap the gap
and a number, in the end, put the gap at the end.
There will be a number 999 in array as gap or space.
Examples:
We follow a recursive approach to solve this problem. As we can only swap numbers with
the space. First of all we find the index of space. If the index is start of array, then move
this space to the second last index by swapping with each number in it’s right.
If space is neither start of array nor last element of array and element before it greater than
the element next to space then do following.
2134
Chapter 333. Sort an array with swapping only with a special element is allowed
Otherwise, elements next to index are sorted and swap it with the previous element. Again
call the sort function with size of array decreased by 1 and index of space – 1 as we will get
one sorted element each time.
2135
Chapter 333. Sort an array with swapping only with a special element is allowed
else
swap(arr[index], arr[index - 1]);
sortRec(arr, index - 1, k - 1, n);
}
// Wrapper over sortRec.
void sort(int arr[], int n)
{
// Find index of space (or 999)
int index = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == 999) {
index = i;
break;
}
}
// Invalid input
if (index == -1)
return;
sortRec(arr, index, n, n);
}
// driver program
int main()
{
int arr[] = { 3, 2, 999, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, n);
return 0;
}
Output:
1 2 3 999
2136
Chapter 333. Sort an array with swapping only with a special element is allowed
Source
https://www.geeksforgeeks.org/sort-array-swapping-special-element-allowed/
2137
Chapter 334
Simple solution is to first convert each array elements into its square and than apply any
“O(nlogn)” sorting algorithm to sort the array elements.
Below is the implementation of above idea
C++
2138
Chapter 334. Sort array after converting elements to their squares
Java
2139
Chapter 334. Sort array after converting elements to their squares
Python3
2140
Chapter 334. Sort array after converting elements to their squares
# This code is contributed by
# Shrikant13
C#
2141
Chapter 334. Sort array after converting elements to their squares
}
}
// This code is contributed by anuj_67.
Output:
Before sort
-6 -3 -1 2 4 5
After Sort
1 4 9 16 25 36
Efficient solution is based on the fact that given array is already sorted. We do following
two steps.
2142
Chapter 334. Sort array after converting elements to their squares
// store sorted array
int temp[n];
while (i >= 0 && j < n)
{
if (arr[i] * arr[i] < arr[j] * arr[j])
{
temp[ind] = arr[i] * arr[i];
i--;
}
else
{
temp[ind] = arr[j] * arr[j];
j++;
}
ind++;
}
/* Copy the remaining elements of first half */
while (i >= 0)
{
temp[ind] = arr[i] * arr[i];
i--;
ind++;
}
/* Copy the remaining elements of second half */
while (j < n)
{
temp[ind] = arr[j] * arr[j];
j++;
ind++;
}
// copy 'temp' array into original array
for (int i = 0 ; i < n; i++)
arr[i] = temp[i];
}
// Driver program to test above function
int main()
{
int arr[] = { -6 , -3 , -1 , 2 , 4 , 5 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Before sort " << endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " " ;
2143
Chapter 334. Sort array after converting elements to their squares
sortSquares(arr, n);
cout << "\nAfter Sort " << endl;
for (int i = 0 ; i < n ; i++)
cout << arr[i] << " " ;
return 0;
}
Java
2144
Chapter 334. Sort array after converting elements to their squares
temp[ind] = arr[j] * arr[j];
j++;
}
ind++;
}
while(i >= 0)
{
temp[ind++] = arr[i] * arr[i];
i--;
}
while(j < n)
{
temp[ind++] = arr[j] * arr[j];
j++;
}
// copy 'temp' array into original array
for (int x = 0 ; x < n; x++)
arr[x] = temp[x];
}
// Driver program to test above function
public static void main (String[] args)
{
int arr[] = { -6 , -3 , -1 , 2 , 4 , 5 };
int n = arr.length;
System.out.println("Before sort ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
sortSquares(arr);
System.out.println("");
System.out.println("After Sort ");
for (int i = 0 ; i < n ; i++)
System.out.print(arr[i] + " ");
}
}
Before sort
-6 -3 -1 2 4 5
After Sort
1 4 9 16 25 36
2145
Chapter 334. Sort array after converting elements to their squares
Source
https://www.geeksforgeeks.org/sort-array-converting-elements-squares/
2146
Chapter 335
Examples:
Example:
Input 2 5 2 8 5 6 8 8
2147
Chapter 335. Sort elements by frequency Set 1
Sort by count
8, 3
2, 2
5, 2
6, 1
Input 5 2 2 8 5 6 8 8
2148
Chapter 335. Sort elements by frequency Set 1
2149
Chapter 335. Sort elements by frequency Set 1
/* Retain the first index (Remember first index
is always present in the first duplicate we
used stable sort. */
element[i].index = element[i-1].index;
}
/* Else If previous element is not equal to current
so set the count to 1 */
else element[i].count = 1;
}
/* Now we have counts and first index for each element so now
sort on the basis of count and in case of tie use index
to sort.*/
stable_sort(element, element+n, mycomp2);
for (int i = n-1, index=0; i >= 0; i--)
if (element[i].count != -1)
for (int j=0; j<element[i].count; j++)
arr[index++] = element[i].val;
}
// Driver program
int main()
{
int arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8};
int n = sizeof(arr)/sizeof(arr[0]);
sortByFrequency(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
8 8 8 2 2 5 5 6 -1 9999999
struct tree
2150
Chapter 335. Sort elements by frequency Set 1
{
int element;
int first_index /*To handle ties in counts*/
int count;
}BST;
Source
https://www.geeksforgeeks.org/sort-elements-by-frequency/
2151
Chapter 336
2152
Chapter 336. Sort elements by frequency Set 2
{
struct BSTNode *left;
int data;
int freq;
struct BSTNode *right;
};
// A structure to store data and its frequency
struct dataFreq
{
int data;
int freq;
};
/* Function for qsort() implementation. Compare frequencies to
sort the array according to decreasing order of frequency */
int compare(const void *a, const void *b)
{
return ( (*(const dataFreq*)b).freq - (*(const dataFreq*)a).freq );
}
/* Helper function that allocates a new node with the given data,
frequency as 1 and NULL left and right pointers.*/
BSTNode* newNode(int data)
{
struct BSTNode* node = new BSTNode;
node->data = data;
node->left = NULL;
node->right = NULL;
node->freq = 1;
return (node);
}
// A utility function to insert a given key to BST. If element
// is already present, then increases frequency
BSTNode *insert(BSTNode *root, int data)
{
if (root == NULL)
return newNode(data);
if (data == root->data) // If already present
root->freq += 1;
else if (data < root->data)
root->left = insert(root->left, data);
else
root->right = insert(root->right, data);
return root;
}
2153
Chapter 336. Sort elements by frequency Set 2
2154
Chapter 336. Sort elements by frequency Set 2
Output:
3 3 3 3 2 2 2 12 12 5 4
Exercise:
The above implementation doesn’t guarantee original order of elements with same frequency
(for example, 4 comes before 5 in input, but 4 comes after 5 in output). Extend the imple-
mentation to maintain original order. For example, if two elements have same frequency
then print the one which came 1st in input array.
This article is compiled by Chandra Prakash. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/sort-elements-by-frequency-set-2/
2155
Chapter 337
1. We insert all elements and their counts into a hash. This step takes O(n) time where
n is number of elements.
2156
Chapter 337. Sort elements by frequency Set 4 (Efficient approach using hash)
2. We copy contents of hash to an array (or vector) and sort them by counts. This step
takes O(m Log m) time where m is total number of distinct elements.
3. For maintaining the order of elements if the frequency is same, we use another hash
which has the key as elements of the array and value as the index. If the frequency is
same for two elements then sort elements according to the index.
2157
Chapter 337. Sort elements by frequency Set 4 (Efficient approach using hash)
Output:
8 8 8 2 2 5 5 6 -1 9999999
Time Complexity : O(n) + O(m Log m) where n is total number of elements and m is total
number of distinct elements
Source
https://www.geeksforgeeks.org/sort-elements-frequency-set-4-efficient-approach-using-hash/
2158
Chapter 338
2. You can use a structure for each element to store its original index and count of factors.
Create an array of such structures to store such information for all the elements.
3. Sort this array of structures on the basis of the problem statement using any sorting
algorithm.
2159
Chapter 338. Sort elements on the basis of number of factors
4. Traverse this array of structures from the beginning and get the number from the
original array with the help of the index stored in the structure of each element of the
sorted array of structures.
C++
2160
Chapter 338. Sort elements on the basis of number of factors
Java
2161
Chapter 338. Sort elements on the basis of number of factors
class Element
{
//each element having its index
// in the input array and number of factors
int index, no_of_fact;
public Element(int i, int countFactors)
{
index = i;
no_of_fact = countFactors;
}
// method to count factors for
// a given number n
static int countFactors(int n)
{
int count = 0;
int sq = (int)Math.sqrt(n);
// if the number is a perfect square
if (sq * sq == n)
count++;
// count all other factors
for (int i=1; i<Math.sqrt(n); i++)
{
// if i is a factor then n/i will be
// another factor. So increment by 2
if (n % i == 0)
count += 2;
}
return count;
}
// function to print numbers after sorting them in
// decreasing order of number of factors
static void printOnBasisOfFactors(int arr[], int n)
{
Element num[] = new Element[n];
// for each element of input array create a
// structure element to store its index and
// factors count
for (int i=0; i<n; i++)
{
num[i] = new Element(i,countFactors(arr[i]));
2162
Chapter 338. Sort elements on the basis of number of factors
}
// sort the array of structures as defined
Arrays.sort(num,new Comparator<Element>() {
@Override
// compare method for the elements
// of the structure
public int compare(Element e1, Element e2) {
// if two elements have the same number
// of factors then sort them in increasing
// order of their index in the input array
if (e1.no_of_fact == e2.no_of_fact)
return e1.index < e2.index ? -1 : 1;
// sort in decreasing order of number of factors
return e1.no_of_fact > e2.no_of_fact ? -1 : 1;
}
});
// access index from the structure element and correponding
// to that index access the element from arr
for (int i=0; i<n; i++)
System.out.print(arr[num[i].index]+" ");
}
// Driver program to test above
public static void main(String[] args)
{
int arr[] = {5, 11, 10, 20, 9, 16, 23};
printOnBasisOfFactors(arr, arr.length);
}
}
// This code is contributed by Gaurav Miglani
Output:
20 16 10 9 5 11 23
2163
Chapter 338. Sort elements on the basis of number of factors
Source
https://www.geeksforgeeks.org/sort-elements-basis-number-factors/
2164
Chapter 339
2165
Chapter 339. Sort even-placed elements in increasing and odd-placed in decreasing order
The idea is simple, we create two auxiliary arrays evenArr[] and oddArr[] respectively. We
traverse input array and put all even-placed elements in evenArr[] and odd placed elements
in oddArr[]. Then we sort evenArr[] in ascending and oddArr[] in descending order. Finally
copy evenArr[] and oddArr[] to get the required result.
2166
Chapter 339. Sort even-placed elements in increasing and odd-placed in decreasing order
Output:
1 2 3 6 8 9 7 5 4 0
2167
Chapter 339. Sort even-placed elements in increasing and odd-placed in decreasing order
}
//Driver Program
int main()
{
int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
int n = sizeof(arr)/sizeof(arr[0]);
bitonicGenerator(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
// This code is contributed by SWARUPANANDA DHUA
Output:
1 2 3 6 8 9 7 5 4 0
Source
https://www.geeksforgeeks.org/sort-even-placed-elements-increasing-odd-placed-decreasing-order/
2168
Chapter 340
Sort first half in ascending and second half in descending order 1 - GeeksforGeeks
Given an array of integers, sort the first half of the array in ascending order and second half
in descending order.
Examples:
Algorithm :
1. Sort the given array.
2. Run a loop upto half the length of the array and print the elements of the sorted array.
3. Run a loop from last index of the array to the middle of the array and print the elements
in reverse order.
Below is the implementation for the same.
C++
2169
Chapter 340. Sort first half in ascending and second half in descending order 1
// function to print half of the array in
// ascending order and the other half in
// descending order
void printOrder(int arr[], int n)
{
// sorting the array
sort(arr, arr + n);
// printing first half in ascending
// order
for (int i = 0; i < n / 2; i++)
cout << arr[i] << " ";
// printing second half in descending
// order
for (int j = n - 1; j >= n / 2; j--)
cout << arr[j] << " ";
}
// driver code
int main()
{
int arr[] = { 5, 4, 6, 2, 1, 3, 8, 9, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
printOrder(arr, n);
return 0;
}
Java
2170
Chapter 340. Sort first half in ascending and second half in descending order 1
// order
for (int i = 0; i < n / 2; i++)
System.out.print(arr[i]+" ");
// printing second half in descending
// order
for (int j = n - 1; j >= n / 2; j--)
System.out.print(arr[j]+" ");
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 5, 4, 6, 2, 1, 3, 8, 9, 7 };
int n = arr.length;
printOrder(arr, n);
}
}
/* This code is contributed by Mr. Somesh Awasthi */
Python
2171
Chapter 340. Sort first half in ascending and second half in descending order 1
print arr[j],
j = j - 1
# Driver code
arr = [5, 4, 6, 2, 1, 3, 8, 9, 7]
n = len(arr)
printOrder(arr, n)
# This code is contributed by Nikita Tiwari.
C#
2172
Chapter 340. Sort first half in ascending and second half in descending order 1
// This code is contributed by vt_m.
PHP
<?php
// PHP program to print first half in
// ascending order and the second half
// in descending order
// function to print half of the array in
// ascending order and the other half in
// descending order
function printOrder($arr, $n)
{
// sorting the array
sort($arr);
// printing first half
// in ascending order
for ($i = 0; $i < intval($n / 2); $i++)
echo $arr[$i] . " ";
// printing second half
// in descending order
for ($j = $n - 1; $j >= intval($n / 2); $j--)
echo $arr[$j] . " ";
}
// Driver Code
$arr = array(5, 4, 6, 2, 1,
3, 8, 9, 7);
$n = count($arr);
printOrder($arr, $n);
// This code is contributed by Sam007
?>
Output:
1 2 3 4 9 8 7 6 5
Alternate Solution :
Here, The elements in the 1st half of array will remain in 1st half but in ascending order
2173
Chapter 340. Sort first half in ascending and second half in descending order 1
among the elements in the 1st half and those in 2nd half of array will remain in 2nd half
but in descending order among the elements in the 2nd half.
1. Sort the 1st half of the array in ascending order just because only the elements in the
1st half of the input array needs to be sorted in ascending order (In this way the original
elements in the 1st half of the array will remain in the 1st half but in ascending order).
2. Sort the 2nd half of the array in descending order just because only the elements in the
2nd half of the input array needs to be sorted in descending order (In this way the original
elements in the 2nd half of the array will remain in the 1st half but in descending order).
Output:
2174
Chapter 340. Sort first half in ascending and second half in descending order 1
-1 1 2 3 8 6 5 4
Sort first half in ascending and second half in descending order Set 2
Improved By : vt_m, Sam007, techmanager2
Source
https://www.geeksforgeeks.org/sort-first-half-in-ascending-and-second-half-in-descending-order/
2175
Chapter 341
Sort first half in ascending and second half in descending order Set 2 - GeeksforGeeks
Given an array of integers, sort the first half of the array in ascending order and second half
in descending order.
Examples:
We have discussed a solution that only prints the required order in Sort first half in ascending
and second half in descending order Set 1
Simple Approach
The idea is simple, we sort the first half in increasing order and second half in decreasing
using library function. Most of the languages like Java, C++ provide provision to sort a
subarray in a specified order. In this post, a different solution is discussed that modifies the
original array.
Java
2176
Chapter 341. Sort first half in ascending and second half in descending order Set 2
C++
Output:
2177
Chapter 341. Sort first half in ascending and second half in descending order Set 2
Alternate Solution
1) Sort the whole array in ascending order.
2) Reverse the second half after sorting.
Java
C++
2178
Chapter 341. Sort first half in ascending and second half in descending order Set 2
void mySort(int arr[], int n)
{
// Sort the first half
sort(arr, arr+n/2);
sort(arr+n/2, arr+n);
reverse(arr+n/2, arr+n);
}
int main()
{
int arr[] = { 5, 4, 6, 2, 1, 3, 8, 9, 7 };
int n = sizeof(arr)/sizeof(arr[0]);
mySort(arr, n);
cout << "Modified Array : \n";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/sort-first-half-in-ascending-and-second-half-in-descending-order-set-2/
2179
Chapter 342
Sort first k values in ascending order and remaining n-k values in descending order - Geeks-
forGeeks
Given an array of size n, arrange the first k elements of the array in ascending order and
the remaining n-k elements in descending order.
Examples:
Algorithm:
1. Store the first k elements in an array and sort that in ascending order.
2. Store the remaining n-k elements in an array and sort that in decending order.
3. Merge the two arrays by adding the elements from second array in reverse order.
C++
2180
Chapter 342. Sort first k values in ascending order and remaining n-k values in
descending order
2181
Chapter 342. Sort first k values in ascending order and remaining n-k values in
descending order
Java
2182
Chapter 342. Sort first k values in ascending order and remaining n-k values in
descending order
// Driver code
public static void main(String[] args)
{
int arr[] = { 5, 4, 6, 2, 1, 3, 8, 9, -1 };
int k = 4;
int n = arr.length;
printOrder(arr, n, k);
}
}
C#
2183
Chapter 342. Sort first k values in ascending order and remaining n-k values in
descending order
Output:
2 4 5 6 9 8 3 1 -1
Efficient Approach: The idea is simple, sort the first k elements in increasing order and
remaining n-k elements in decreasing using library function.
C++
2184
Chapter 342. Sort first k values in ascending order and remaining n-k values in
descending order
Java
2185
Chapter 342. Sort first k values in ascending order and remaining n-k values in
descending order
printOrder(arr, k);
System.out.printf("%s",Arrays.toString(arr));
}
}
Output:
2 4 5 6 9 8 3 1 -1
Improved By : tufan_gupta2000
Source
https://www.geeksforgeeks.org/sort-first-k-values-in-ascending-order-and-remaining-n-k-values-in-descending-order
2186
Chapter 343
Examples:
Since there are 5 elements, the elements can be from 0 to 24.
Input: arr[] = {0, 23, 14, 12, 9}
Output: arr[] = {0, 9, 12, 14, 23}
Solution: If we use Counting Sort, it would take O(n^2) time as the given range is of
size n^2. Using any comparison based sorting likeMerge Sort, Heap Sort, .. etc would take
O(nLogn) time.
Now question arises how to do this in 0(n)? Firstly, is it possible? Can we use data given
in question? n numbers in range from 0 to n2 – 1?
The idea is to use Radix Sort. Following is standard Radix Sort algorithm.
Let there be d digits in input integers. Radix Sort takes O(d*(n+b)) time where b is the
base for representing numbers, for example, for decimal system, b is 10. Since n2 -1 is the
2187
Chapter 343. Sort n numbers in range from 0 to n^2 – 1 in linear time
maximum possible value, the value of d would be O(logb (n)). So overall time complexity
is O((n+b)*O(logb (n)). Which looks more than the time complexity of comparison based
sorting algorithms for a large k. The idea is to change base b. If we set b as n, the value of
O(logb (n)) becomes O(1) and overall time complexity becomes O(n).
Following is the implementation to sort an array of size n where elements are in range from
0 to n2 – 1.
C++
#include<iostream>
using namespace std;
// A function to do counting sort of arr[] according to
// the digit represented by exp.
int countSort(int arr[], int n, int exp)
{
int output[n]; // output array
int i, count[n] ;
for (int i=0; i < n; i++)
count[i] = 0;
// Store count of occurrences in count[]
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%n ]++;
// Change count[i] so that count[i] now contains actual
// position of this digit in output[]
for (i = 1; i < n; i++)
count[i] += count[i - 1];
// Build the output array
for (i = n - 1; i >= 0; i--)
2188
Chapter 343. Sort n numbers in range from 0 to n^2 – 1 in linear time
{
output[count[ (arr[i]/exp)%n] - 1] = arr[i];
count[(arr[i]/exp)%n]--;
}
// Copy the output array to arr[], so that arr[] now
// contains sorted numbers according to curent digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}
// The main function to that sorts arr[] of size n using Radix Sort
void sort(int arr[], int n)
{
// Do counting sort for first digit in base n. Note that
// instead of passing digit number, exp (n^0 = 1) is passed.
countSort(arr, n, 1);
// Do counting sort for second digit in base n. Note that
// instead of passing digit number, exp (n^1 = n) is passed.
countSort(arr, n, n);
}
// A utility function to print an array
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver program to test above functions
int main()
{
// Since array size is 7, elements should be from 0 to 48
int arr[] = {40, 12, 45, 32, 33, 1, 22};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Given array is n";
printArr(arr, n);
sort(arr, n);
cout << "nSorted array is n";
printArr(arr, n);
return 0;
}
Java
2189
Chapter 343. Sort n numbers in range from 0 to n^2 – 1 in linear time
2190
Chapter 343. Sort n numbers in range from 0 to n^2 – 1 in linear time
C#
2191
Chapter 343. Sort n numbers in range from 0 to n^2 – 1 in linear time
count[i] = 0;
// Store count of
// occurrences in count[]
for (i = 0; i < n; i++)
count[(arr[i] / exp) % n ]++;
// Change count[i] so that
// count[i] now contains actual
// position of this digit in output[]
for (i = 1; i < n; i++)
count[i] += count[i - 1];
// Build the output array
for (i = n - 1; i >= 0; i--)
{
output[count[(arr[i] /
exp) % n] - 1] = arr[i];
count[(arr[i] / exp) % n]--;
}
// Copy the output array to
// arr[], so that arr[] now
// contains sorted numbers
// according to curent digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}
// The main function to that
// sorts arr[] of size n
// using Radix Sort
static void sort(int[] arr, int n)
{
// Do counting sort for first
// digit in base n. Note that
// instead of passing digit number,
// exp (n^0 = 1) is passed.
countSort(arr, n, 1);
// Do counting sort for second
// digit in base n. Note that
// instead of passing digit number,
// exp (n^1 = n) is passed.
countSort(arr, n, n);
}
2192
Chapter 343. Sort n numbers in range from 0 to n^2 – 1 in linear time
// A utility function
// to print an array
static void printArr(int[] arr, int n)
{
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
// Driver Code
static public void Main ()
{
// Since array size is 7,
// elements should be
// from 0 to 48
int[] arr = {40, 12, 45, 32, 33, 1, 22};
int n = arr.Length;
Console.WriteLine("Given array");
printArr(arr, n);
sort(arr, n);
Console.WriteLine("\nSorted array");
printArr(arr, n);
}
}
// This code is contributed by Ajit.
Output:
Given array is
40 12 45 32 33 1 22
Sorted array is
1 12 22 32 33 40 45
2193
Chapter 343. Sort n numbers in range from 0 to n^2 – 1 in linear time
This article is contributed by Bateesh. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : Rahul-Chauhan, jit_t
Source
https://www.geeksforgeeks.org/sort-n-numbers-range-0-n2-1-linear-time/
2194
Chapter 344
Example:
Machine M1 contains 3 numbers: {30, 40, 50}
Machine M2 contains 2 numbers: {35, 45}
Machine M3 contains 5 numbers: {10, 60, 70, 80, 100}
Output: {10, 30, 35, 40, 45, 50, 60, 70, 80, 100}
// A program to take numbers from different machines and print them in sorted order
2195
Chapter 344. Sort numbers stored on different machines
#include <stdio.h>
// A Linked List node
struct ListNode
{
int data;
struct ListNode* next;
};
// A Min Heap Node
struct MinHeapNode
{
ListNode* head;
};
// A Min Heao (Collection of Min Heap nodes)
struct MinHeap
{
int count;
int capacity;
MinHeapNode* array;
};
// A function to create a Min Heap of given capacity
MinHeap* createMinHeap( int capacity )
{
MinHeap* minHeap = new MinHeap;
minHeap->capacity = capacity;
minHeap->count = 0;
minHeap->array = new MinHeapNode [minHeap->capacity];
return minHeap;
}
/* A utility function to insert a new node at the begining
of linked list */
void push (ListNode** head_ref, int new_data)
{
/* allocate node */
ListNode* new_node = new ListNode;
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
2196
Chapter 344. Sort numbers stored on different machines
}
// A utility function to swap two min heap nodes. This function
// is needed in minHeapify
void swap( MinHeapNode* a, MinHeapNode* b )
{
MinHeapNode temp = *a;
*a = *b;
*b = temp;
}
// The standard minHeapify function.
void minHeapify( MinHeap* minHeap, int idx )
{
int left, right, smallest;
left = 2 * idx + 1;
right = 2 * idx + 2;
smallest = idx;
if ( left < minHeap->count &&
minHeap->array[left].head->data <
minHeap->array[smallest].head->data
)
smallest = left;
if ( right < minHeap->count &&
minHeap->array[right].head->data <
minHeap->array[smallest].head->data
)
smallest = right;
if( smallest != idx )
{
swap( &minHeap->array[smallest], &minHeap->array[idx] );
minHeapify( minHeap, smallest );
}
}
// A utility function to check whether a Min Heap is empty or not
int isEmpty( MinHeap* minHeap )
{
return (minHeap->count == 0);
}
// A standard function to build a heap
void buildMinHeap( MinHeap* minHeap )
{
int i, n;
2197
Chapter 344. Sort numbers stored on different machines
n = minHeap->count - 1;
for( i = (n - 1) / 2; i >= 0; --i )
minHeapify( minHeap, i );
}
// This function inserts array elements to heap and then calls
// buildHeap for heap property among nodes
void populateMinHeap( MinHeap* minHeap, ListNode* *array, int n )
{
for( int i = 0; i < n; ++i )
minHeap->array[ minHeap->count++ ].head = array[i];
buildMinHeap( minHeap );
}
// Return minimum element from all linked lists
ListNode* extractMin( MinHeap* minHeap )
{
if( isEmpty( minHeap ) )
return NULL;
// The root of heap will have minimum value
MinHeapNode temp = minHeap->array[0];
// Replace root either with next node of the same list.
if( temp.head->next )
minHeap->array[0].head = temp.head->next;
else // If list empty, then reduce heap size
{
minHeap->array[0] = minHeap->array[ minHeap->count - 1 ];
--minHeap->count;
}
minHeapify( minHeap, 0 );
return temp.head;
}
// The main function that takes an array of lists from N machines
// and generates the sorted output
void externalSort( ListNode *array[], int N )
{
// Create a min heap of size equal to number of machines
MinHeap* minHeap = createMinHeap( N );
// populate first item from all machines
populateMinHeap( minHeap, array, N );
while ( !isEmpty( minHeap ) )
2198
Chapter 344. Sort numbers stored on different machines
{
ListNode* temp = extractMin( minHeap );
printf( "%d ",temp->data );
}
}
// Driver program to test above functions
int main()
{
int N = 3; // Number of machines
// an array of pointers storing the head nodes of the linked lists
ListNode *array[N];
// Create a Linked List 30->40->50 for first machine
array[0] = NULL;
push (&array[0], 50);
push (&array[0], 40);
push (&array[0], 30);
// Create a Linked List 35->45 for second machine
array[1] = NULL;
push (&array[1], 45);
push (&array[1], 35);
// Create Linked List 10->60->70->80 for third machine
array[2] = NULL;
push (&array[2], 100);
push (&array[2], 80);
push (&array[2], 70);
push (&array[2], 60);
push (&array[2], 10);
// Sort all elements
externalSort( array, N );
return 0;
}
Output:
10 30 35 40 45 50 60 70 80 100
Source
https://www.geeksforgeeks.org/sort-numbers-stored-on-different-machines/
2199
Chapter 345
We have already discussed a structure based solution to sort according to number of factors.
The following steps sort numbers in decreasing order of count of factors.
3. Sort this array on the basis of the problem statement using any sorting algorithm.
2200
Chapter 345. Sort on the basis of number of factors using STL
2201
Chapter 345. Sort on the basis of number of factors using STL
// Driver's Function
int main() {
int arr[] = {5, 11, 10, 20, 9, 16, 23};
int n = sizeof(arr) / sizeof(arr[0]);
printSorted(arr, n);
return 0;
}
Output:
20 16 10 9 5 11 23
Source
https://www.geeksforgeeks.org/sort-basis-number-factors-using-stl/
2202
Chapter 346
Input : bbccdefbbaa
Output : aabbbbccdef
Input : geeksforgeeks
Output : eeeefggkkorss
A simple approach will be to use sorting algorithms like quick sort or merge sort and sort
the input string and print it.
C++
2203
Chapter 346. Sort string of characters
string s = "geeksforgeeks";
sortString(s);
return 0;
}
Output:
eeeefggkkorss
2204
Chapter 346. Sort string of characters
Java
2205
Chapter 346. Sort string of characters
Output:
eeeefggkkorss
Source
https://www.geeksforgeeks.org/sort-string-characters/
2206
Chapter 347
Approach:
•
• if the ith character is greater than or equal to the top element of the stack, then push
the element.
• if the ith character is not greater, then push all the elements of the stack into temp-
stack, and then push the character into the stack. After this, push all the greater
elements of tempstack to stack.
Print the all elements of the stack in reverse order when the iteration is completed.
Below is the implementation of the above approach:
2207
Chapter 347. Sort string of characters using Stack
2208
Chapter 347. Sort string of characters using Stack
stack.append(s[i])
# push the tempstack back to stack
while(len(tempstack)>0):
stack.append(tempstack.pop())
# print the stack in reverse order
print(''.join(stack))
# Driver Code
s = "geeksforgeeks"
l = len(s)
printSorted(s, l)
Output:
eeeefggkkorss
Source
https://www.geeksforgeeks.org/sort-string-of-characters-using-stack/
2209
Chapter 348
Approach: Find the first node in the list which is smaller than its previous node. Let it be
current. If no such node is present then list is already sorted. Else split the list into two
lists, first starting from head node till the current’s previous node and second starting
from current node till the end of the list. Reverse the second doubly linked list. Refer this
post. Now merge the first and second sorted doubly linked list. Refer merge procedure of
this post. The final merged list is the required sorted doubly linked list.
2210
Chapter 348. Sort the biotonic doubly linked list
2211
Chapter 348. Sort the biotonic doubly linked list
// function to sort a biotonic doubly linked list
struct Node* sort(struct Node* head)
{
// if list is empty or if it contains a single
// node only
if (head == NULL || head->next == NULL)
return head;
struct Node* current = head->next;
while (current != NULL) {
// if true, then 'current' is the first node
// which is smaller than its previous node
if (current->data < current->prev->data)
break;
// move to the next node
current = current->next;
}
// if true, then list is already sorted
if (current == NULL)
return head;
// spilt into two lists, one starting with 'head'
// and other starting with 'current'
current->prev->next = NULL;
current->prev = NULL;
// reverse the list starting with 'current'
reverse(¤t);
// merge the two lists and return the
// final merged doubly linked list
return merge(head, current);
}
// Function to insert a node at the beginning
// of the Doubly Linked List
void push(struct Node** head_ref, int new_data)
{
// allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// put in the data
2212
Chapter 348. Sort the biotonic doubly linked list
new_node->data = new_data;
// since we are adding at the begining,
// prev is always NULL
new_node->prev = NULL;
// link the old list off the new node
new_node->next = (*head_ref);
// change prev of head node to new node
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
// move the head to point to the new node
(*head_ref) = new_node;
}
// Function to print nodes in a given doubly
// linked list
void printList(struct Node* head)
{
// if list is empty
if (head == NULL)
cout << "Doubly Linked list empty";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
struct Node* head = NULL;
// Create the doubly linked list:
// 2<->5<->7<->12<->10<->6<->4<->1
push(&head, 1);
push(&head, 4);
push(&head, 6);
push(&head, 10);
push(&head, 12);
push(&head, 7);
push(&head, 5);
push(&head, 2);
cout << "Original Doubly linked list:n";
2213
Chapter 348. Sort the biotonic doubly linked list
printList(head);
// sort the biotonic DLL
head = sort(head);
cout << "\nDoubly linked list after sorting:n";
printList(head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/sort-biotonic-doubly-linked-list/
2214
Chapter 349
Approach: Create a temp[] array of size n^2. Starting with the first row one by one
copy the elements of the given matrix into temp[]. Sort temp[]. Now one by one copy the
elements of temp[] back to the given matrix.
C++
2215
Chapter 349. Sort the given matrix
2216
Chapter 349. Sort the given matrix
Java
2217
Chapter 349. Sort the given matrix
int mat[][] = { { 5, 4, 7 },
{ 1, 3, 8 },
{ 2, 9, 6 } };
int n = 3;
System.out.println("Original Matrix:");
printMat(mat, n);
sortMat(mat, n);
System.out.println("Matrix After Sorting:");
printMat(mat, n);
}
}
// This code is contributed by Nikita Tiwari.
Python3
2218
Chapter 349. Sort the given matrix
for i in range(0, n) :
for j in range(0, n) :
mat[i][j] = temp[k]
k += 1
# Function to print the given matrix
def printMat(mat, n) :
for i in range(0, n) :
for j in range( 0, n ) :
print(mat[i][j] , end = " ")
print()
# Driver program to test above
mat = [ [ 5, 4, 7 ],
[ 1, 3, 8 ],
[ 2, 9, 6 ] ]
n = 3
print( "Original Matrix:")
printMat(mat, n)
sortMat(mat, n)
print("\nMatrix After Sorting:")
printMat(mat, n)
# This code is contributed by Nikita Tiwari.
C#
// C# implementation to
// sort the given matrix
using System;
class GFG {
static int SIZE = 10;
// function to sort the given matrix
static void sortMat(int[, ] mat, int n)
{
2219
Chapter 349. Sort the given matrix
2220
Chapter 349. Sort the given matrix
// This code is contributed by Sam007
Output :
Original Matrix:
5 4 7
1 3 8
2 9 6
Source
https://www.geeksforgeeks.org/sort-given-matrix/
2221
Chapter 350
Input : geeksforgeeks
Output : eeeefggkkorss
Input : coding
Output : cdgino
Algorithm:
sortString(str, n)
Initialize new_str = ""
return new_str
C++
2222
Chapter 350. Sort the given string using character search
Java
2223
Chapter 350. Sort the given string using character search
Python3
2224
Chapter 350. Sort the given string using character search
return new_str
# Driver Code
str = "geeksforgeeks"
n = len(str)
print(sortString(str, n))
# This code is contributed by Anant Agarwal.
C#
2225
Chapter 350. Sort the given string using character search
Output :
eeeefggkkorss
Source
https://www.geeksforgeeks.org/sort-given-string-using-character-search/
2226
Chapter 351
Sort the linked list in the order of elements appearing in the array - GeeksforGeeks
Given an array of size N and a Linked List where elements will be from the array but can
also be duplicated, sort the linked list in the order, elements are appearing in the array. It
may be assumed that the array covers all elements of the linked list.
arr[] =
list =
Sorted list =
Asked in Amazon
First, make a hash table that stores the frequencies of elements in linked list. Then, simply
traverse list and for each element of arr[i] check the frequency in the has table and modify
the data of list by arr[i] element upto its frequency and at last Print the list.
2227
Chapter 351. Sort the linked list in the order of elements appearing in the array
2228
Chapter 351. Sort the linked list in the order of elements appearing in the array
Output :
Sort list:
5 -> 5 -> 1 -> 3 -> 2 -> 2 -> 8
2229
Chapter 351. Sort the linked list in the order of elements appearing in the array
Source
https://www.geeksforgeeks.org/sort-linked-list-order-elements-appearing-array/
2230
Chapter 352
2231
Chapter 352. Sort the matrix row-wise and column-wise
Algorithm for sorting each row of matrix using C++ STL sort():
C++
2232
Chapter 352. Sort the matrix row-wise and column-wise
swap(mat[i][j], mat[j][i]);
}
// function to sort the matrix row-wise
// and column-wise
void sortMatRowAndColWise(int mat[MAX_SIZE][MAX_SIZE],
int n)
{
// sort rows of mat[][]
sortByRow(mat, n);
// get transpose of mat[][]
transpose(mat, n);
// again sort rows of mat[][]
sortByRow(mat, n);
// again get transpose of mat[][]
transpose(mat, n);
}
// function to print the matrix
void printMat(int mat[MAX_SIZE][MAX_SIZE], int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
// Driver program to test above
int main()
{
int mat[MAX_SIZE][MAX_SIZE] = { { 4, 1, 3 },
{ 9, 6, 8 },
{ 5, 2, 7 } };
int n = 3;
cout << "Original Matrix:\n";
printMat(mat, n);
sortMatRowAndColWise(mat, n);
cout << "\nMatrix After Sorting:\n";
printMat(mat, n);
return 0;
2233
Chapter 352. Sort the matrix row-wise and column-wise
Java
2234
Chapter 352. Sort the matrix row-wise and column-wise
Python 3
2235
Chapter 352. Sort the matrix row-wise and column-wise
2236
Chapter 352. Sort the matrix row-wise and column-wise
print("Original Matrix:")
printMat(mat, n)
sortMatRowAndColWise(mat, n)
print("\nMatrix After Sorting:")
printMat(mat, n)
# This code is contributed
# by ChitraNayal
C#
2237
Chapter 352. Sort the matrix row-wise and column-wise
2238
Chapter 352. Sort the matrix row-wise and column-wise
{9, 6, 8},
{5, 2, 7}};
int n = 3;
Console.Write("Original Matrix:\n");
printMat(mat, n);
sortMatRowAndColWise(mat, n);
Console.Write("\nMatrix After Sorting:\n");
printMat(mat, n);
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// PHP implementation to sort
// the matrix row-wise and
// column-wise
$MAX_SIZE = 10;
// function to sort each
// row of the matrix
function sortByRow(&$mat, $n)
{
for ($i = 0; $i < $n; $i++)
// sorting row number 'i'
sort($mat[$i]);
}
// function to find
// transpose of the matrix
function transpose(&$mat, $n)
{
for ($i = 0; $i < $n; $i++)
{
for ($j = $i + 1;
$j < $n; $j++)
{
// swapping element at index (i, j)
// by element at index (j, i)
$t = $mat[$i][$j];
$mat[$i][$j] = $mat[$j][$i];
2239
Chapter 352. Sort the matrix row-wise and column-wise
$mat[$j][$i] = $t;
}
}
}
// function to sort
// the matrix row-wise
// and column-wise
function sortMatRowAndColWise(&$mat, $n)
{
// sort rows of mat[][]
sortByRow($mat, $n);
// get transpose of mat[][]
transpose($mat, $n);
// again sort rows of mat[][]
sortByRow($mat, $n);
// again get transpose of mat[][]
transpose($mat, $n);
}
// function to print the matrix
function printMat(&$mat, $n)
{
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
echo $mat[$i][$j] . " ";
echo "\n";
}
}
// Driver Code
$mat = array(array( 4, 1, 3 ),
array( 9, 6, 8 ),
array( 5, 2, 7 ));
$n = 3;
echo "Original Matrix:\n";
printMat($mat, $n);
sortMatRowAndColWise($mat, $n);
echo "\nMatrix After Sorting:\n";
printMat($mat, $n);
2240
Chapter 352. Sort the matrix row-wise and column-wise
Output:
Original Matrix:
4 1 3
9 6 8
5 2 7
Source
https://www.geeksforgeeks.org/sort-matrix-row-wise-column-wise/
2241
Chapter 353
Note: The words which have first letter is capital letter they will print according alphabetical
manner.
Approach :
Approach used in this program is very simple. Split the strings using split() function. After
that sort the words in lexicographical order using sort(). Iterate the words through loop
and print each word, which are already sorted.
2242
Chapter 353. Sort the words in lexicographical order in Python
# order
def sortLexo(my_string):
# Split the my_string till where space is found.
words = my_string.split()
# sort() will sort the strings.
words.sort()
# Iterate i through 'words' to print the words
# in alphabetical manner.
for i in words:
print( i )
# Driver code
if __name__ == '__main__':
my_string = "hello this is example how to sort " \
"the word in alphabetical manner"
# Calling function
sortLexo(my_string)
Output :
alphabetical
example
hello
how
in
is
manner
sort
the
this
to
word
Source
https://www.geeksforgeeks.org/sort-words-lexicographical-order-python/
2243
Chapter 354
Sorting 2D Vector in C++ Set 2 (In descending order by row and column) - GeeksforGeeks
We have discussed some of the cases of sorting 2D vector in below set 1.
Sorting 2D Vector in C++ Set 1 (By row and column)
More cases are discussed in this article
Case 3 : To sort a particular row of 2D vector in descending order
This type of sorting arranges a selected row of 2D vector in descending order . This is
achieved by using “sort()” and passing iterators of 1D vector as its arguments.
2244
Chapter 354. Sorting 2D Vector in C++ Set 2 (In descending order by row and column)
// Number of columns (Assuming all rows
// are of same size). We can have different
// sizes though (like Java).
int n = vect[0].size();
// Displaying the 2D vector before sorting
cout << "The Matrix before sorting 1st row is:\n";
for (int i=0; i<m; i++)
{
for (int j=0; j<n ;j++)
cout << vect[i][j] << " ";
cout << endl;
}
// Use of "sort()" for sorting first row
sort(vect[0].rbegin(), vect[0].rend());
// Displaying the 2D vector after sorting
cout << "The Matrix after sorting 1st row is:\n";
for (int i=0; i<m; i++)
{
for (int j=0; j<n ;j++)
cout << vect[i][j] << " ";
cout << endl;
}
return 0;
}
Output:
2245
Chapter 354. Sorting 2D Vector in C++ Set 2 (In descending order by row and column)
{3, 5, 1},
{4, 8, 6},
{7, 2, 9};
After sorting this matrix by second column, we get
{4, 8, 6} // Row with greatest value in second column
{3, 5, 1} // Row with second greatest value in second column
{7, 2, 9}
This is achieved by passing a third argument in “sort()” as a call to user defined explicit
function.
2246
Chapter 354. Sorting 2D Vector in C++ Set 2 (In descending order by row and column)
Output:
Source
https://www.geeksforgeeks.org/sorting-2d-vector-in-c-set-2-in-descending-order-by-row-and-column/
2247
Chapter 355
2248
Chapter 355. Sorting 2D Vector in C++ Set 3 (By number of columns)
Output:
1 2
3 4 5
6
2249
Chapter 355. Sorting 2D Vector in C++ Set 3 (By number of columns)
Output:
2250
Chapter 355. Sorting 2D Vector in C++ Set 3 (By number of columns)
2251
Chapter 355. Sorting 2D Vector in C++ Set 3 (By number of columns)
Output:
Source
https://www.geeksforgeeks.org/sorting-2d-vector-c-set-3-number-columns/
2252
Chapter 356
2253
Chapter 356. Sorting Array Elements By Frequency Set 3 (Using STL)
// STL
#include <bits/stdc++.h>
using namespace std;
// function to compare two pairs for inbuilt sort
bool compare(pair<int,int> &p1,
pair<int, int> &p2)
{
// If frequencies are same, compare
// values
if (p1.second == p2.second)
return p1.first < p2.first;
return p1.second > p2.second;
}
// function to print elements sorted by freq
void printSorted(int arr[], int n)
{
// Store items and their frequencies
map<int, int> m;
for (int i = 0; i < n; i++)
m[arr[i]]++;
// no of distinct values in the array
// is equal to size of map.
int s = m.size();
// an array of pairs
pair<int, int> p[s];
// Fill (val, freq) pairs in an array
// of pairs.
int i = 0;
for (auto it = m.begin(); it != m.end(); ++it)
p[i++] = make_pair(it->first, it->second);
// sort the array of pairs using above
// compare function.
sort(p, p + s, compare);
cout << "Elements sorted by frequency are: ";
for (int i = 0; i < s; i++)
{
int freq = p[i].second;
while (freq--)
cout << p[i].first << " ";
}
}
2254
Chapter 356. Sorting Array Elements By Frequency Set 3 (Using STL)
// driver program
int main()
{
int arr[] = {2, 3, 2, 4, 5, 12, 2, 3,
3, 3, 12};
int n = sizeof(arr)/ sizeof(arr[0]);
printSorted(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/sorting-array-elements-frequency-set-3-using-stl/
2255
Chapter 357
A naive approach is to use arbitrary precision data type such as int in python or Bigin-
teger class in Java. But that approach will not be fruitful because internal conversion of
string to int and then perform sorting will leads to slow down the calculations of addition
and multiplications in binary number system.
Efficient Solution : As size of integer is very large even it can’t be fit in long long data
type of C/C++, so we just need to input all numbers as strings and sort them using a
comparison function. Following are the key points compare function:-
1. If lengths of two strings are different, then we need to compare lengths to decide
sorting order.
2. If Lengths are same then we just need to compare both the strings in lexicographically
order.
2256
Chapter 357. Sorting Big Integers
Python
2257
Chapter 357. Sorting Big Integers
Time complexity: O(sum * log(n)) where sum is the total sum of all string length and n
is size of array
Auxiliary space: O(n)
Similar Post :
Sort an array of large numbers
Source
https://www.geeksforgeeks.org/sorting-big-integers/
2258
Chapter 358
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
void sortStrings(char arr[][MAX], int n)
{
char temp[MAX];
// Sorting strings using bubble sort
for (int j=0; j<n-1; j++)
{
for (int i=j+1; i<n; i++)
{
if (strcmp(arr[j], arr[i]) > 0)
{
strcpy(temp, arr[j]);
2259
Chapter 358. Sorting Strings using Bubble Sort
strcpy(arr[j], arr[i]);
strcpy(arr[i], temp);
}
}
}
}
int main()
{
char arr[][MAX] = {"GeeksforGeeks","Quiz","Practice","Gblogs","Coding"};
int n = sizeof(arr)/sizeof(arr[0]);
sortStrings(arr, n);
printf("Strings in sorted order are : ");
for (int i=0; i<n; i++)
printf("\n String %d is %s", i+1, arr[i]);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/sorting-strings-using-bubble-sort-2/
2260
Chapter 359
Sorting Terminology
Source
https://www.geeksforgeeks.org/sorting-terminology/
2261
Chapter 360
Sorting Vector of Pairs in C++ Set 1 (Sort by first and second) - GeeksforGeeks
What is Vector of Pairs?
A pair is a container which stores two values mapped to each other, and a vector containing
multiple number of such pairs is called a vector of pairs.
2262
Chapter 360. Sorting Vector of Pairs in C++ Set 1 (Sort by first and second)
Output:
10 30
20 60
5 20
40 50
Case 1 : Sorting the vector elements on the basis of first element of pairs in
ascending order.
This type of sorting can be achieved using simple “ sort() ” function. By default the sort
function sorts the vector elements on basis of first element of pairs.
2263
Chapter 360. Sorting Vector of Pairs in C++ Set 1 (Sort by first and second)
Output:
Case 2 : Sorting the vector elements on the basis of second element of pairs in
ascending order.
There are instances when we require to sort the elements of vector on the basis of second
elements of pair. For that, we modify the sort() function and we pass a third argument, a
call to an user defined explicit function in the sort() function.
2264
Chapter 360. Sorting Vector of Pairs in C++ Set 1 (Sort by first and second)
2265
Chapter 360. Sorting Vector of Pairs in C++ Set 1 (Sort by first and second)
Output:
Source
https://www.geeksforgeeks.org/sorting-vector-of-pairs-in-c-set-1-sort-by-first-and-second/
2266
Chapter 361
Sorting Vector of Pairs in C++ Set 2 (Sort in descending order by first and second) -
GeeksforGeeks
We have discussed some of the cases of sorting vector of pairs in below set 1.
Sorting Vector of Pairs in C++ Set 1 (Sort by first and second)
More cases are discussed in this article
Sometimes we require to sort the vector in reverse order. In those instances, rather than
first sorting the vector and later using “reverse” function increases time complexity of code.
Therefore, to avoid this we sort the vector in descending order directly.
Case 3 : Sorting the vector elements on the basis of first element of pairs in
descending order.
For these instances, we modify the sort() function and we pass a third argument, a call to
an user defined explicit function in the sort() function.
2267
Chapter 361. Sorting Vector of Pairs in C++ Set 2 (Sort in descending order by first and
second)
{
return (a.first > b.first);
}
int main()
{
// declaring vector of pairs
vector< pair <int,int> > vect;
// initializing 1st and 2nd element of
// pairs with array values
int arr[] = {5, 20, 10, 40 };
int arr1[] = {30, 60, 20, 50};
int n = sizeof(arr)/sizeof(arr[0]);
// Entering values in vector of pairs
for (int i=0; i<n; i++)
vect.push_back( make_pair(arr[i],arr1[i]) );
// Printing the original vector(before sort())
cout << "The vector before applying sort is:\n" ;
for (int i=0; i<n; i++)
{
// "first" and "second" are used to access
// 1st and 2nd element of pair respectively
cout << vect[i].first << " "
<< vect[i].second << endl;
}
// using modified sort() function to sort
sort(vect.begin(), vect.end(), sortinrev);
// Printing the sorted vector(after using sort())
cout << "The vector after applying sort is:\n" ;
for (int i=0; i<n; i++)
{
// "first" and "second" are used to access
// 1st and 2nd element of pair respectively
cout << vect[i].first << " "
<< vect[i].second << endl;
}
return 0;
}
Output:
2268
Chapter 361. Sorting Vector of Pairs in C++ Set 2 (Sort in descending order by first and
second)
Case 4 : Sorting the vector elements on the basis of second element of pairs in
descending order.
These instances can also be handled by modifying “sort()” function and again passing a call
to user defined function.
2269
Chapter 361. Sorting Vector of Pairs in C++ Set 2 (Sort in descending order by first and
second)
Output:
Source
https://www.geeksforgeeks.org/sorting-vector-of-pairs-in-c-set-2-sort-in-descending-order-by-first-and-second/
2270
Chapter 362
1. enqueue() : Adds an item to rear of queue. In C++ STL queue, this function is called
push().
2. dequeue() : Removes an item from front of queue. In C++ STL queue, this function
is called pop().
3. isEmpty() : Checks if a queue is empty. In C++ STL queue, this function is called
empty().
Examples :
2271
Chapter 362. Sorting a Queue without extra space
If we are allowed extra space, then we can simply move all items of queue to an array, then
sort the array and finally move array elements back to queue.
How to do without extra space?
The idea: on every pass on the queue, we seek for the next minimum index. To do this we
dequeue and enqueue elements until we find the next minimum. In this operation the queue
is not changed at all. After we have found the minimum index, we dequeue and enqueue
elements from the queue except for the minimum index, after we finish the traversal in the
queue we insert the minimum to the rear of the queue. We keep on this until all minimums
are pushed all way long to the front and the queue becomes sorted.
On every next seeking for the minimum, we exclude seeking on the minimums that have
already sorted.
We repeat this method n times.
At first we seek for the maximum, because on every pass we need find the next minimum,
so we need to compare it with the largest element in the queue.
Illustration:
Input :
-------------
11 5 4 21 min index = 2
-------------
-------------
11 5 21 4 after inserting 4
-------------
-------------
11 5 21 4 min index = 1
-------------
-------------
11 21 4 5 after inserting 5
-------------
-------------
11 21 4 5 min index = 0
-------------
-------------
21 4 5 11 after inserting 11
-------------
-------------
21 4 5 11 min index = 0
-------------
-------------
4 5 11 21 after inserting 21
-------------
Output : 4 5 11 21
2272
Chapter 362. Sorting a Queue without extra space
C++
2273
Chapter 362. Sorting a Queue without extra space
else
min_val = curr;
}
q.push(min_val);
}
void sortQueue(queue<int> &q)
{
for (int i = 1; i <= q.size(); i++)
{
int min_index = minIndex(q, q.size() - i);
insertMinToRear(q, min_index);
}
}
// driver code
int main()
{
queue<int> q;
q.push(30);
q.push(11);
q.push(15);
q.push(4);
// Sort queue
sortQueue(q);
// Print sorted queue
while (q.empty() == false)
{
cout << q.front() << " ";
q.pop();
}
cout << endl;
return 0;
}
Java
2274
Chapter 362. Sorting a Queue without extra space
// sortIndex
public static int minIndex(Queue<Integer> list,
int sortIndex)
{
int min_index = -1;
int min_value = Integer.MAX_VALUE;
int s = list.size();
for (int i = 0; i < s; i++)
{
int current = list.peek();
// This is dequeue() in Java STL
list.poll();
// we add the condition i <= sortIndex
// because we don't want to traverse
// on the sorted part of the queue,
// which is the right part.
if (current <= min_value && i <= sortIndex)
{
min_index = i;
min_value = current;
}
list.add(current);
}
return min_index;
}
// Moves given minimum element
// to rear of queue
public static void insertMinToRear(Queue<Integer> list,
int min_index)
{
int min_value = 0;
int s = list.size();
for (int i = 0; i < s; i++)
{
int current = list.peek();
list.poll();
if (i != min_index)
list.add(current);
else
min_value = current;
}
list.add(min_value);
}
public static void sortQueue(Queue<Integer> list)
2275
Chapter 362. Sorting a Queue without extra space
{
for(int i = 1; i <= list.size(); i++)
{
int min_index = minIndex(list,list.size() - i);
insertMinToRear(list, min_index);
}
}
//Driver function
public static void main (String[] args)
{
Queue<Integer> list = new LinkedList<Integer>();
list.add(30);
list.add(11);
list.add(15);
list.add(4);
//Sort Queue
sortQueue(list);
//print sorted Queue
while(list.isEmpty()== false)
{
System.out.print(list.peek() + " ");
list.poll();
}
}
}
// This code is contributed by akash1295
C#
// C# program to implement
// sorting a queue data structure
using System;
using System.Collections.Generic;
class GFG
{
// Queue elements after sorted
// Index are already sorted.
// This function returns index
// of minimum element from front
// to sortedIndex
static int minIndex(ref Queue<int> q,
int sortedIndex)
{
2276
Chapter 362. Sorting a Queue without extra space
2277
Chapter 362. Sorting a Queue without extra space
{
int min_index = minIndex(ref q,
q.Count - i);
insertMinToRear(ref q,
min_index);
}
}
// Driver Code
static void Main()
{
Queue<int> q = new Queue<int>();
q.Enqueue(30);
q.Enqueue(11);
q.Enqueue(15);
q.Enqueue(4);
// Sort queue
sortQueue(ref q);
// Print sorted queue
while (q.Count != 0)
{
Console.Write(q.Peek() + " ");
q.Dequeue();
}
Console.WriteLine();
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output:
4 11 15 30
Source
https://www.geeksforgeeks.org/sorting-queue-without-extra-space/
2278
Chapter 363
A simple solution is to copy all elements except k-th of given array to another array.
Then sort the other array using a sorting algorithm. Finally again copy the sorted array to
original array. While copying, skip k-th element.
Below is an efficient solution.
C++
2279
Chapter 363. Sorting all array elements except one
Java
2280
Chapter 363. Sorting all array elements except one
C#
2281
Chapter 363. Sorting all array elements except one
PHP
<?php
// PHP program to sort all
// elements except element
// at index k.
function sortExceptK(&$arr, $k, $n)
{
// Move k-th element to end
$t = $arr[$k];
$arr[$k] = $arr[$n - 1];
$arr[$n - 1] = $t;
2282
Chapter 363. Sorting all array elements except one
// Sort all elements
// except last
$t = $arr[count($arr) - 1];
$arr = array_slice($arr, 0, -1);
sort($arr);
array_push($arr, $t);
// Store last element
// (originally k-th)
$last = $arr[$n - 1];
// Move all elements from
// k-th to one position ahead.
for ($i = $n - 1; $i > $k; $i--)
$arr[$i] = $arr[$i - 1];
// Restore k-th element
$arr[$k] = $last;
}
// Driver code
$a = array(10, 4, 11,
7, 6, 20 );
$k = 2;
$n = count($a);
sortExceptK($a, $k, $n);
for ($i = 0; $i < $n; $i++)
echo ($a[$i]." ");
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
4 6 11 7 10 20
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/sorting-array-elements-except-one/
2283
Chapter 364
Input : 2 1 5 4 9 3 6 7 10 8
A B C D E F G H I J
Output : 1 2 3 4 5 6 7 8 9 10
B A F D C G H J E I
Here we are sorting second array
(a character array) according to
the first array (an integer array).
2284
Chapter 364. Sorting an array according to another array using pair in STL
Output:
2285
Chapter 364. Sorting an array according to another array using pair in STL
1 2 3 4 5 6 7 8 9 10
B A F D C G H J E I
Improved By : cs_abhi
Source
https://www.geeksforgeeks.org/sorting-array-according-another-array-using-pair-stl/
2286
Chapter 365
Approach : Copy all elements except the given limit of given array to another array. Then
sort the other array using a sorting algorithm. Finally again copy the sorted array to original
array. While copying, skip given subarray.
C++
2287
Chapter 365. Sorting array except elements in a subarray
Java
2288
Chapter 365. Sorting array except elements in a subarray
Python3
2289
Chapter 365. Sorting array except elements in a subarray
C#
2290
Chapter 365. Sorting array except elements in a subarray
// Copy all those element that need
// to be sorted to an auxiliary
// array b[]
int[] b = new int[n - (u-l+1)];
for (int i = 0; i < l; i++)
b[i] = a[i];
for (int i = u+1; i < n; i++)
b[l + (i - (u+1))] = a[i];
// sort the array b
Array.Sort<int>(b, 0, n - (u - l + 1));
// Copy sorted elements back to a[]
for (int i = 0; i < l; i++)
a[i] = b[i];
for (int i = u+1; i < n; i++)
a[i] = b[l + (i - (u+1))];
}
// Driver code
public static void Main()
{
int []a = { 5, 4, 3, 12, 14, 9 };
int n = a.Length;
int l = 2, u = 4;
sortExceptUandL(a, l, u, n);
for (int i = 0; i < n; i++)
Console.Write(a[i] + " ");
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP program to sort all
// elements except given subarray.
// Sort whole array a[] except
// elements in range a[l..r]
2291
Chapter 365. Sorting array except elements in a subarray
Output :
4 5 3 12 14 9
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/sorting-array-except-elements-subarray/
2292
Chapter 366
Trie is an efficient data structure used for storing data like strings. To print the string in
alphabetical order we have to first insert in the trie and then perform preorder traversal to
print in alphabetical order.
2293
Chapter 366. Sorting array of strings (or words) using Trie
// index is set when node is a leaf
// node, otherwise -1;
int index;
Trie* child[MAX_CHAR];
/*to make new trie*/
Trie()
{
for (int i = 0; i < MAX_CHAR; i++)
child[i] = NULL;
index = -1;
}
};
/* function to insert in trie */
void insert(Trie* root, string str, int index)
{
Trie* node = root;
for (int i = 0; i < str.size(); i++) {
/* taking ascii value to find index of
child node */
char ind = str[i] - 'a';
/* making new path if not already */
if (!node->child[ind])
node->child[ind] = new Trie();
// go to next node
node = node->child[ind];
}
// Mark leaf (end of word) and store
// index of word in arr[]
node->index = index;
}
/* function for preorder traversal */
bool preorder(Trie* node, string arr[])
{
if (node == NULL)
return false;
for (int i = 0; i < MAX_CHAR; i++) {
if (node->child[i] != NULL) {
2294
Chapter 366. Sorting array of strings (or words) using Trie
/* if leaf node then print key*/
if (node->child[i]->index != -1)
cout << arr[node->child[i]->index] << endl;
preorder(node->child[i], arr);
}
}
}
void printSorted(string arr[], int n)
{
Trie* root = new Trie();
// insert all keys of dictionary into trie
for (int i = 0; i < n; i++)
insert(root, arr[i], i);
// print keys in lexicographic order
preorder(root, arr);
}
// Driver code
int main()
{
string arr[] = { "abc", "xy", "bcd" };
int n = sizeof(arr) / sizeof(arr[0]);
printSorted(arr, n);
return 0;
}
Output:
abc bcd xy
Source
https://www.geeksforgeeks.org/sorting-array-strings-words-using-trie/
2295
Chapter 367
Sorting array of strings (or words) using Trie Set-2 (Handling Duplicates) - GeeksforGeeks
Given an array of strings, print them in alphabetical (dictionary) order. If there are dupli-
cates in input array, we need to print all the occurrences.
Examples:
2296
Chapter 367. Sorting array of strings (or words) using Trie Set-2 (Handling Duplicates)
2297
Chapter 367. Sorting array of strings (or words) using Trie Set-2 (Handling Duplicates)
Java
// Java implementation
// to sort an array of
// strings using Trie
2298
Chapter 367. Sorting array of strings (or words) using Trie Set-2 (Handling Duplicates)
import java.util.*;
class Trie {
private Node rootNode;
/*to make new trie*/
Trie()
{
rootNode = null;
}
// function to insert
// a string in trie
void insert(String key, int index)
{
// making a new path
// if not already
if (rootNode == null)
{
rootNode = new Node();
}
Node currentNode = rootNode;
for (int i = 0;i < key.length();i++)
{
char keyChar = key.charAt(i);
if (currentNode.getChild(keyChar) == null)
{
currentNode.addChild(keyChar);
}
// go to next node
currentNode = currentNode.getChild(keyChar);
}
// Mark leaf (end of string)
// and store index of 'str'
// in index[]
currentNode.addIndex(index);
}
void traversePreorder(String[] array)
{
traversePreorder(rootNode, array);
}
2299
Chapter 367. Sorting array of strings (or words) using Trie Set-2 (Handling Duplicates)
// function for preorder
// traversal of trie
private void traversePreorder(Node node,
String[] array)
{
if (node == null)
{
return;
}
if (node.getIndices().size() > 0)
{
for (int index : node.getIndices())
{
System.out.print(array[index] + " ");
}
}
for (char index = 'a';index <= 'z';index++)
{
traversePreorder(node.getChild(index), array);
}
}
private static class Node {
private Node[] children;
private List<Integer> indices;
Node()
{
children = new Node[26];
indices = new ArrayList<>(0);
}
Node getChild(char index)
{
if (index < 'a' || index > 'z')
{
return null;
}
return children[index - 'a'];
}
void addChild(char index)
{
2300
Chapter 367. Sorting array of strings (or words) using Trie Set-2 (Handling Duplicates)
2301
Chapter 367. Sorting array of strings (or words) using Trie Set-2 (Handling Duplicates)
Output:
Source
https://www.geeksforgeeks.org/sorting-array-strings-words-using-trie-set-2-handling-duplicates/
2302
Chapter 368
Input : 8 5 7 1 9 12 10
Output : 1 5 7 8 9 10 12
Explanation :
Output is sorted element set
Input : 7 4 10 20 2 5 9 1
Output : 1 2 4 5 7 9 10 20
We basically use Sort a stack using a temporary stack. Then we put sorted stack elements
back to array.
C++
2303
Chapter 368. Sorting array using Stacks
2304
Chapter 368. Sorting array using Stacks
Java
2305
Chapter 368. Sorting array using Stacks
static void sortArrayUsingStacks(int []arr,
int n)
{
// push array elements
// to stack
Stack<Integer> input =
new Stack<Integer>();
for (int i = 0; i < n; i++)
input.push(arr[i]);
// Sort the temporary stack
Stack<Integer> tmpStack =
sortStack(input);
// Put stack elements
// in arrp[]
for (int i = 0; i < n; i++)
{
arr[i] = tmpStack.peek();
tmpStack.pop();
}
}
// Driver Code
public static void main(String args[])
{
int []arr = {10, 5, 15, 45};
int n = arr.length;
sortArrayUsingStacks(arr, n);
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
C#
2306
Chapter 368. Sorting array using Stacks
{
// This function return
// the sorted stack
static Stack<int> sortStack(Stack<int> input)
{
Stack<int> tmpStack = new Stack<int>();
while (input.Count != 0)
{
// pop out the
// first element
int tmp = input.Peek();
input.Pop();
// while temporary stack is
// not empty and top of stack
// is smaller than temp
while (tmpStack.Count != 0 &&
tmpStack.Peek() < tmp)
{
// pop from temporary
// stack and push it
// to the input stack
input.Push(tmpStack.Peek());
tmpStack.Pop();
}
// push temp in
// tempory of stack
tmpStack.Push(tmp);
}
return tmpStack;
}
static void sortArrayUsingStacks(int []arr,
int n)
{
// Push array elements
// to stack
Stack<int> input = new Stack<int>();
for (int i = 0; i<n; i++)
input.Push(arr[i]);
// Sort the temporary stack
Stack<int> tmpStack = sortStack(input);
// Put stack elements in arrp[]
2307
Chapter 368. Sorting array using Stacks
Output:
5 10 15 45
Source
https://www.geeksforgeeks.org/sorting-array-using-stacks/
2308
Chapter 369
Sorting in Java
1. Arrays.Sort() works for arrays which can be of primitive data type also.
Output:
2309
Chapter 369. Sorting in Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Create a list of strings
ArrayList<String> al = new ArrayList<String>();
al.add("Geeks For Geeks");
al.add("Friends");
al.add("Dear");
al.add("Is");
al.add("Superb");
/* Collections.sort method is sorting the
elements of ArrayList in ascending order. */
Collections.sort(al);
// Let us print the sorted list
System.out.println("List after the use of"
+ " Collection.sort() :\n" + al);
}
}
1. For Arrays.sort()
// A sample Java program to sort an array
// in descending order using Arrays.sort().
import java.util.Arrays;
import java.util.Collections;
public class GFG {
public static void main(String[] args)
{
// Note that we have Integer here instead of
// int[] as Collections.reverseOrder doesn't
// work for primitive types.
Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
2310
Chapter 369. Sorting in Java
Output:
2311
Chapter 369. Sorting in Java
// using Arrays.sort().
import java.util.Arrays;
public class GFG {
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
// Sort subarray from index 1 to 4, i.e.,
// only sort subarray {7, 6, 45, 21} and
// keep other elements as it is.
Arrays.sort(arr, 1, 5);
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
}
}
Output:
Source
https://www.geeksforgeeks.org/sorting-in-java/
2312
Chapter 370
Output:
2313
Chapter 370. Sorting of Vector of Tuple in C++ (Ascending Order)
10 20 30
15 5 25
3 2 1
Output:
2314
Chapter 370. Sorting of Vector of Tuple in C++ (Ascending Order)
Case 2 : Sorting the vector elements on the basis of second element of tuples
in ascending order.
There are instances when we require to sort the elements of vector on the basis of second
elements of tuples. For that, we modify the sort() function and we pass a third argument,
a call to an user defined explicit function in the sort() function.
Output:
2315
Chapter 370. Sorting of Vector of Tuple in C++ (Ascending Order)
Case 3 : Sorting the vector elements on the basis of third element of tuples in
ascending order.
There are instances when we require to sort the elements of vector on the basis of third
elements of tuples. For that, we modify the sort() function and we pass a third argument,
a call to an user defined explicit function in the sort() function.
Output:
Improved By : suri_kumkaran
2316
Chapter 370. Sorting of Vector of Tuple in C++ (Ascending Order)
Source
https://www.geeksforgeeks.org/sorting-vector-tuple-c-ascending-order/
2317
Chapter 371
Sorting rows of matrix in ascending order followed by columns in descending order - Geeks-
forGeeks
Given a matrix, sort the rows of matrix in ascending order followed by sorting the columns
in descending order.
Examples :
1) Traverse all rows one by one and sort rows in ascending order using simple array sort.
2) Convert matrix to its transpose
3) Again sort all rows, but this time in ascending order.
4) Again convert matrix to its transpose
C++
2318
Chapter 371. Sorting rows of matrix in ascending order followed by columns in descending
order
2319
Chapter 371. Sorting rows of matrix in ascending order followed by columns in descending
order
// again get transpose of mat[][]
transpose(mat, n);
}
// function to print the matrix
void printMat(int mat[][MAX_SIZE], int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
// Driver program to test above
int main()
{
int n = 3;
int mat[n][MAX_SIZE] = {{3, 2, 1},
{9, 8, 7},
{6, 5, 4}};
cout << "Original Matrix:\n";
printMat(mat, n);
sortMatRowAndColWise(mat, n);
cout << "\nMatrix After Sorting:\n";
printMat(mat, n);
return 0;
}
Java
2320
Chapter 371. Sorting rows of matrix in ascending order followed by columns in descending
order
2321
Chapter 371. Sorting rows of matrix in ascending order followed by columns in descending
order
Python3
2322
Chapter 371. Sorting rows of matrix in ascending order followed by columns in descending
order
mat[i].sort(reverse=True)
# function to find
# transpose of the matrix
def transpose(mat, n):
for i in range(n):
for j in range(i + 1, n):
# swapping element at index (i, j)
# by element at index (j, i)
temp = mat[i][j]
mat[i][j] = mat[j][i]
mat[j][i] = temp
# function to sort
# the matrix row-wise
# and column-wise
def sortMatRowAndColWise(mat, n):
# sort rows of mat[][]
sortByRow(mat, n, True)
# get transpose of mat[][]
transpose(mat, n)
# again sort rows of
# mat[][] in descending
# order.
sortByRow(mat, n, False)
# again get transpose of mat[][]
transpose(mat, n)
# function to print the matrix
def printMat(mat, n):
for i in range(n):
for j in range(n):
print(mat[i][j] , " ", end="")
print()
#Driver code
n = 3
mat = [[3, 2, 1],
[9, 8, 7],
[6, 5, 4]]
2323
Chapter 371. Sorting rows of matrix in ascending order followed by columns in descending
order
print("Original Matrix:")
printMat(mat, n)
sortMatRowAndColWise(mat, n)
print("Matrix After Sorting:")
printMat(mat, n)
# This code is contributed
# by Anant Agarwal.
Output :
Original Matrix:
3 2 1
9 8 7
6 5 4
Source
https://www.geeksforgeeks.org/sorting-rows-matrix-ascending-order-followed-sorting-columns-descending-order/
2324
Chapter 372
Input : 9 4 3 5 8
Output : 3 4 5 8 9
We have read about various sorting algorithms such as heap sort, bubble sort, merge sort
and others.
Here we will see how can we sort N elements using hash array. But this algorithm has a
limitation. We can sort only those N elements, where the value of elements is not large
(typically not above 10^6).
Explanation of sorting using hash:
Step 1: create a hash array of size(max_element), since that is the maximum we will need
Step 2: traverse through all the elements and keep a count of number of occurrence of a
particular element.
Step 3: after keep a count of occurrence of all elements in the hash table, simply iterate
from 0 to max_element in the hash array
Step 4: while iterating in the hash array, if we find the value stored at any hash position
is more then 0, which indicated that the element is present at least once in the original list
of elements.
Step 5: Hash[i] has the count of the number of times a element is present in the list, so
when its >0, we print those number of times the element.
If you want to store the elements, use another array to store them in a sorted way.
If we want to sort it in a descending order, we simply traverse from max to 0, and repeat
the same procedure.
2325
Chapter 372. Sorting using trivial hash function
2326
Chapter 372. Sorting using trivial hash function
return 0;
}
Output:
0 1 2 2 3 3 4 4 5 5 9 10 12 15 18 19 20
2327
Chapter 372. Sorting using trivial hash function
Output:
2328
Chapter 372. Sorting using trivial hash function
-6 -5 -4 -3 -2 -1 0 1 2 3 4 5 7 8
Complexity:
This sort function can have complexity O(max_element). So performance depends on that
set of data provided.
Limitations:
1. Can only sort array elements of limited range (typically from -10^6 to +10^6)
2. Auxiliary space in worst cases is O(max_element) + O(min_element)
Source
https://www.geeksforgeeks.org/sorting-using-trivial-hash-function/
2329
Chapter 373
We are not allowed to use comparison based sorting algorithms like QuickSort, MergeSort,
etc.
Since elements are small, we use array elements as index. We store element counts in a
count array. Once we have count array, we traverse the count array and print every present
element its count times.
2330
Chapter 373. Sorting without comparison of elements
{
// Count of elements in given range
int m = max - min + 1;
// Count frequencies of all elements
vector<int> c(m, 0);
for (int i=0; i<n; i++)
c[arr[i] - min]++;
// Traverse through range. For every
// element, print it its count times.
for (int i=0; i<=m; i++)
for (int j=0; j < c[i]; j++)
cout << (i + min) << " ";
}
int main()
{
int arr[] = {10, 10, 1, 4, 4, 100, 0};
int min = 0, max = 100;
int n = sizeof(arr)/sizeof(arr[0]);
sortArr(arr, n, min, max);
return 0;
}
Output:
0 1 4 4 10 10 100
Source
https://www.geeksforgeeks.org/sorting-without-comparison-of-elements/
2331
Chapter 374
When the word “thing” appears in a type definition, our compiler works a little magic behind
the scenes to make things (pun intended) more powerful and flexible. The above definition,
for example, actually causes the following data types to be defined:
2332
Chapter 374. Sorting Natural Language Programming
So a Fruit is really nothing but a pointer containing the address of a Fruit Record.
And each 16-byte Fruit Record has a hidden 8-byte prefix with two pointers for linking these
records into lists, together with the fruit’s name, which is a string. Plain English strings
are stored in the Heap and can be any length. So the Name in the Fruit Record is actually
just two pointers to the first and last bytes of the string on the Heap, respectively. String
memory is managed automatically, but thing memory is managed by the programmer.
The third type generated by the compiler serves as the anchor for lists of Fruit Records.
Such lists are simply (and intuitively) called Fruits, the plural of Fruit.
Now let’s add some fruits to a list, in random order, and sort them. Here are the top level
sentences in our test program:
To run:
Start up.
Create some fruits.
Write the fruits on the console.
Skip a line on the console.
Sort the fruits.
Write the fruits on the console.
Destroy the fruits.
Wait for the escape key.
Shut down.
And here are the routines that will be called to “Create some fruits”:
2333
Chapter 374. Sorting Natural Language Programming
When we run this program, the output on the console looks like this:
2334
Chapter 374. Sorting Natural Language Programming
To run:
Start up.
Write "Working..." on the console.
Put 10000 into a count.
Create some fruits using "apple" and the count.
Start a timer. Sort the fruits. Stop the timer.
Write the timer then " milliseconds for " then the count on the console.
Destroy the fruits.
Put 100000 into the count.
Create the fruits using "apple" and the count.
Start the timer. Sort the fruits. Stop the timer.
2335
Chapter 374. Sorting Natural Language Programming
Write the timer then " milliseconds for " then the count on the console.
Destroy the fruits.
Put 1000000 into the count.
Create the fruits using "apple" and the count.
Start the timer. Sort the fruits. Stop the timer.
Write the timer then " milliseconds for " then the count on the console.
Destroy the fruits.
Wait for the escape key.
Shut down.
apple 0010000
apple 0009999
apple 0009998
...
Not quite linear, I admit. But not exponentially bad, either. Ten times as many records
take roughly ten times as long to sort. There’s a technical way of saying this using big “O’s”
and little “n’s’ and “logs” and stuff, but Plain English programmers don’t generally think
that way. And it’s stable, as a Plain English programmer would expect — records with
duplicate sort values retain their original sequence.
Good, simple, useful stuff.
Source
https://www.geeksforgeeks.org/natural-language-programming-sorting/
2336
Chapter 375
2337
Chapter 375. Stability in sorting algorithms
When equal elements are indistinguishable, such as with integers, or more generally, any
data where the entire element is the key, stability is not an issue. Stability is also not an
issue if all keys are different.
An example where it is useful
Consider the following dataset of Student Names and their respective class sections.
If we sort this data according to name only, then it is highly unlikely that the resulting
dataset will be grouped according to sections as well.
So we might have to sort again to obtain list of students section wise too. But in doing so,
if the sorting algorithm is not stable, we might get a result like this-
The dataset is now sorted according to sections, but not according to names.
2338
Chapter 375. Stability in sorting algorithms
Here the relative order between different tuples is maintained. It may be the case that the
relative order is maintained in an Unstable Sort but that is highly unlikely.
Which sorting algorithms are stable?
Some Sorting Algorithms are stable by nature, such as Bubble Sort, Insertion Sort, Merge
Sort, Count Sort etc.
Comparison based stable sorts such as Merge Sort and Insertion Sort, maintain stability by
ensuring that-
indices and .
before .
Other non-comparison based sorts such as Counting Sort maintain stability by ensuring that
the Sorted Array is filled in a reverse order so that elements with equivalent keys have the
same relative position.
Some sorts such as Radix Sort depend on another sort, with the only requirement that the
other sort should be stable.
Which sorting algorithms are unstable?
Quick Sort, Heap Sort etc., can be made stable by also taking the position of the elements
into consideration. This change may be done in a way which does not compromise a lot on
2339
Chapter 375. Stability in sorting algorithms
Source
https://www.geeksforgeeks.org/stability-in-sorting-algorithms/
2340
Chapter 376
Input : 4A 5 3 2 4B 1
Output : 1 2 3 4B 4A 5
Selection sortworks by finding the minimum element and then inserting it in its correct
position by swapping with the element which is in the position of this minimum element.
This is what makes it unstable.
Swapping might impact in pushing a key(let’s say A) to a position greater than the key(let’s
say B) which are equal keys. which makes them out of desired order.
In the above example 4A was pushed after 4B and after complete sorting this 4A remains
after this 4B . Hence resulting in unstability.
Selection sort can be made Stable if instead of swapping, the minimum element is placed in
its position without swapping i.e. by placing the number in its position by pushing every
element one step forward.
2341
Chapter 376. Stable Selection Sort
In simple terms use a technique like insertion sort which means inserting element in its
correct place.
EXPLANATION WITH EXAMPLE:
Example: 4A 5 3 2 4B 1
First minimum element is 1, now instead
of swapping. Insert 1 in its correct place
and pushing every element one step forward
i.e forward pushing.
1 4A 5 3 2 4B
Next minimum is 2 :
1 2 4A 5 3 4B
Next minimum is 3 :
1 2 3 4A 5 3 2 4B
Repeat the steps until array is sorted.
1 2 3 4A 4B 5
C++
2342
Chapter 376. Stable Selection Sort
}
a[i] = key;
}
}
void printArray(int a[], int n)
{
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int a[] = { 4, 5, 3, 2, 4, 1 };
int n = sizeof(a) / sizeof(a[0]);
stableSelectionSort(a, n);
printArray(a, n);
return 0;
}
Java
2343
Chapter 376. Stable Selection Sort
C#
2344
Chapter 376. Stable Selection Sort
Output:
1 2 3 4 4 5
Improved By : vt_m
Source
https://www.geeksforgeeks.org/stable-selection-sort/
2345
Chapter 377
2346
Chapter 377. Stable sort for descending order
C++
Java
2347
Chapter 377. Stable sort for descending order
import java.io.*;
import java.util.*;
class GFG
{
static void print(ArrayList<Integer> a,
int n)
{
for (int i = 0; i <= n; i++)
System.out.print(a.get(i) + " ");
System.out.println();
}
// Sorts a[] in descending
// order using bubble sort.
static void sort(ArrayList<Integer> a,
int n)
{
for (int i = n;
i >= 0; i--)
for (int j = n;
j > n - i; j--)
if (a.get(j) > a.get(j - 1))
{
int tempswap = a.get(j);
a.remove(j);
a.add(j, a.get(j - 1));
a.remove(j - 1);
a.add(j - 1, tempswap);
}
print(a, n);
}
// Driver code
public static void main(String[] args)
{
int n = 6;
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(2);
a.add(4);
a.add(3);
a.add(2);
a.add(4);
a.add(5);
a.add(3);
sort(a, n);
}
}
2348
Chapter 377. Stable sort for descending order
// This code is contributed by
// Manish Shaw(manishshaw1)
Python3
C#
2349
Chapter 377. Stable sort for descending order
int n)
{
for (int i = 0; i <= n; i++)
Console.Write(a[i] + " ");
Console.WriteLine();
}
// Sorts a[] in descending
// order using bubble sort.
static void sort(List<int> a,
int n)
{
for (int i = n;
i >= 0; i--)
for (int j = n;
j > n - i; j--)
if (a[j] > a[j - 1])
{
int tempswap = a[j];
a[j] = a[j - 1];
a[j - 1] = tempswap;
}
print(a, n);
}
// Driver code
static void Main()
{
int n = 6;
List<int> a = new List<int>();
a.Add(2);
a.Add(4);
a.Add(3);
a.Add(2);
a.Add(4);
a.Add(5);
a.Add(3);
sort(a, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
<?php
// Bubble sort implementation
2350
Chapter 377. Stable sort for descending order
// to sort elements in
// descending order.
function swap(&$x, &$y)
{
$x ^= $y ^= $x ^= $y;
}
function print1($a, $n)
{
for ($i = 0; $i <= $n; $i++)
echo ($a[$i] . " ");
echo ("\n");
}
// Sorts a[] in descending
// order using bubble sort.
function sort1($a, $n)
{
for ($i = $n;
$i >= 0; $i--)
{
for ($j = $n;
$j > $n - $i; $j--)
{
if ($a[$j] > $a[$j - 1])
swap($a[$j],
$a[$j - 1]);
}
}
print1($a, $n);
}
// Driver code
$n = 6;
$a = array();
array_push($a, 2);
array_push($a, 4);
array_push($a, 3);
array_push($a, 2);
array_push($a, 4);
array_push($a, 5);
array_push($a, 3);
sort1($a, $n);
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
2351
Chapter 377. Stable sort for descending order
Output:
5 4 4 3 3 2 2
Output:
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/stable-sort-descending-order/
2352
Chapter 378
Stooge Sort
Illustration:
Input : 2 4 5 3 1
Output : 1 2 3 4 5
Explanation:
Initially, swap 2 and 1 following above step 1.
1 4 5 3 2
Now, recursively sort initial 2/3rd of the elements.
1 4 5 3 2
1 3 4 5 2
Then, recursively sort last 2/3rd of the elements.
1 3 4 5 2
1 2 3 4 5
Again, sort the initial 2/3rd of the elements to confirm final data is sorted.
1 2 3 4 5
2353
Chapter 378. Stooge Sort
C++
2354
Chapter 378. Stooge Sort
int t = (h - l + 1) / 3;
// Recursively sort first 2/3 elements
stoogesort(arr, l, h - t);
// Recursively sort last 2/3 elements
stoogesort(arr, l + t, h);
// Recursively sort first 2/3 elements
// again to confirm
stoogesort(arr, l, h - t);
}
}
// Driver Code
int main()
{
int arr[] = { 2, 4, 5, 3, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
// Calling Stooge Sort function to sort
// the array
stoogesort(arr, 0, n - 1);
// Display the sorted array
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Java
2355
Chapter 378. Stooge Sort
arr[h] = t;
}
// If there are more than 2 elements in
// the array
if (h - l + 1 > 2) {
int t = (h - l + 1) / 3;
// Recursively sort first 2/3 elements
stoogesort(arr, l, h - t);
// Recursively sort last 2/3 elements
stoogesort(arr, l + t, h);
// Recursively sort first 2/3 elements
// again to confirm
stoogesort(arr, l, h - t);
}
}
// Driver Code
public static void main(String args[])
{
int arr[] = { 2, 4, 5, 3, 1 };
int n = arr.length;
stoogesort(arr, 0, n - 1);
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
// Code Contributed by Mohit Gupta_OMG <(0_o)>
Python3
2356
Chapter 378. Stooge Sort
# If there are more than 2 elements in
# the array
if h-l + 1 > 2:
t = (int)((h-l + 1)/3)
# Recursively sort first 2 / 3 elements
stoogesort(arr, l, (h-t))
# Recursively sort last 2 / 3 elements
stoogesort(arr, l + t, (h))
# Recursively sort first 2 / 3 elements
# again to confirm
stoogesort(arr, l, (h-t))
# deriver
arr = [2, 4, 5, 3, 1]
n = len(arr)
stoogesort(arr, 0, n-1)
for i in range(0, n):
print(arr[i], end = ' ')
# Code Contributed by Mohit Gupta_OMG <(0_o)>
C#
2357
Chapter 378. Stooge Sort
}
// If there are more than 2
// elements in the array
if (h - l + 1 > 2) {
int t = (h - l + 1) / 3;
// Recursively sort first
// 2/3 elements
stoogesort(arr, l, h - t);
// Recursively sort last
// 2/3 elements
stoogesort(arr, l + t, h);
// Recursively sort first
// 2/3 elements again to
// confirm
stoogesort(arr, l, h - t);
}
}
// Driver Code
public static void Main()
{
int[] arr = { 2, 4, 5, 3, 1 };
int n = arr.Length;
// Calling Stooge Sort function
// to sort the array
stoogesort(arr, 0, n - 1);
// Display the sorted array
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Sam007.
Output:
1 2 3 4 5
2358
Chapter 378. Stooge Sort
Source
https://www.geeksforgeeks.org/stooge-sort/
2359
Chapter 379
Strand Sort
Strand Sort is a sorting algorithm that works in O(n) time if list is already sorted and works
in O(n*n) in worst case.
Below are simple steps used in the algorithm.
3. Traverse remaining items of ip. For every item x, check if x is greater than last inserted
item to sublist. If yes, remove x from ip and add at the end of sublist. If no, ignore x
(Keep it it in ip)
4. Merge sublist into op (output list)
Illustration :
2360
Chapter 379. Strand Sort
Below is the implementation of above algorithm. The C++ implementation uses list in C++
STL.
2361
Chapter 379. Strand Sort
2362
Chapter 379. Strand Sort
// Sorting the list
strandSort(ip, op);
// Printing the sorted list
for (auto x : op)
cout << x << " ";
return 0;
}
Output:
2 4 5 9 10 30 40
• Selection Sort
• Bubble Sort
• Recursive Bubble Sort
• Insertion Sort
• Recursive Insertion Sort
• Merge Sort
• Iterative Merge Sort
• Quick Sort
• Bucket Sort
• ShellSort
• TimSort
• Comb Sort
• Pigeonhole Sort
• Cycle Sort
2363
Chapter 379. Strand Sort
• Bitonic Sort
• Cocktail Sort
• Pancake sorting
• Binary Insertion Sort
• BogoSort or Permutation Sort
• Gnome Sort
• Sleep Sort – The King of Laziness / Sorting while Sleeping
• Structure Sorting (By Multiple Rules) in C++
• Stooge Sort
Source
https://www.geeksforgeeks.org/strand-sort/
2364
Chapter 380
1. If total marks are different, then students with higher marks gets better rank.
2. If total marks are same, then students with higher marks in Maths gets better rank.
3. If total marks are same and marks in Maths are also same, then students with better
marks in Physics gets better rank.
4. If all marks (total, Maths, Physics and Chemistry) are same, then any student can be
assigned bedtter rank.
struct Student
{
string name; // Given
int math; // Marks in math (Given)
int phy; // Marks in Physics (Given)
int che; // Marks in Chemistry (Given)
int total; // Total marks (To be filled)
int rank; // Rank of student (To be filled)
};
2365
Chapter 380. Structure Sorting (By Multiple Rules) in C++
We use std::sort() for Structure Sorting. In Structure sorting, all the respective properties
possessed by the structure object are sorted on the basis of one (or more) property of the
object.
In this example, marks of students in different subjects are provided by user. These marks
in individual subjects are added to calculate the total marks of the student, which is then
used to sort different students on the basis of their ranks (as explained above).
2366
Chapter 380. Structure Sorting (By Multiple Rules) in C++
// Assigning ranks after sorting
for (int i=0; i<n; i++)
a[i].rank = i+1;
}
// Driver code
int main()
{
int n = 5;
// array of structure objects
Student a[n];
// Details of Student 1
a[0].name = "Bryan" ;
a[0].math = 80 ;
a[0].phy = 95 ;
a[0].che = 85 ;
// Details of Student 2
a[1].name= "Kevin" ;
a[1].math= 95 ;
a[1].phy= 85 ;
a[1].che= 99 ;
// Details of Student 3
a[2].name = "Nick" ;
a[2].math = 95 ;
a[2].phy = 85 ;
a[2].che = 80 ;
// Details of Student 4
a[3].name = "AJ" ;
a[3].math = 80 ;
a[3].phy = 70 ;
a[3].che = 90 ;
// Details of Student 5
a[4].name = "Howie" ;
a[4].math = 80 ;
a[4].phy = 80 ;
a[4].che = 80 ;
computeRanks(a, n);
//Column names for displaying data
cout << "Rank" <<"t" << "Name" << "t";
2367
Chapter 380. Structure Sorting (By Multiple Rules) in C++
Output:
Related Articles:
sort() in C++ STL
Comparator function of qsort() in C
C qsort() vs C++ sort()
Sort an array according to count of set bits
Source
https://www.geeksforgeeks.org/structure-sorting-in-c/
2368
Chapter 381
Substring Sort
Observation 1
If A substring of B
Then length of A <= length of B
Observation 2
If (A substring of B ) and (B substring of C)
Then A substring of C
Solution
Based on the two above observations, the solutions is as follows
2369
Chapter 381. Substring Sort
If we validate that each string is a substring of the following string then based on observation
2, each string is a substring of all the strings come after it.
2370
Chapter 381. Substring Sort
substringSort(arr2, arr2.length);
}
}
Output:
d
ds
dds
ddsaa
Cannot be sorted
Complexity
Time Complexity: O(n log n), where n is the number of strings.
Alternative approach
For better time complexity, we can usecounting sort only if the maximum length of the
strings is specified.
Suppose that ‘maxLen’ is the maximum length of the input strings. In this case, the solution
is as follows:
2371
Chapter 381. Substring Sort
String s = arr[i];
int len = s.length();
if (count[len - 1] == 0) {
sortedArr[len - 1] = s;
count[len - 1] = 1;
}
else if (sortedArr[len - 1].equals(s)) {
// repeated length should be the same string
count[len - 1]++;
}
else {
// two different strings with the same
// length input array cannot be sorted
System.out.println("Cannot be sorted");
return;
}
}
// validate that each string is a substring
// of the following one
int index = 0;
// get first element
while (count[index] == 0)
index++;
int prev = index;
String prevString = sortedArr[prev];
index++;
for (; index < maxLen; index++) {
if (count[index] != 0) {
String current = sortedArr[index];
if (current.contains(prevString)) {
prev = index;
prevString = current;
}
else {
System.out.println("Cannot be sorted");
return;
}
}
2372
Chapter 381. Substring Sort
}
// The array is valid and sorted
// print the strings in order
for (int i = 0; i < maxLen; i++) {
String s = sortedArr[i];
for (int j = 0; j < count[i]; j++) {
System.out.println(s);
}
}
}
public static void main(String[] args)
{
int maxLen = 100;
// Test 1
String[] arr1 = { "d", "zddsaaz", "ds", "ddsaa",
"dds", "dds" };
substringSort(arr1, arr1.length, maxLen);
// Test 2
String[] arr2 = { "for", "rof" };
substringSort(arr2, arr2.length, maxLen);
}
}
Output:
d
ds
dds
dds
ddsaa
zddsaaz
Cannot be sorted
Source
https://www.geeksforgeeks.org/substring-sort/
2373
Chapter 382
Input : a = { 3, 4, 5, 6 }
Output : 15
Explanation :
We can reduce 4 to 3 and 6 to 5 so that we got
rectangle of (3 * 5). Hence area = 15.
Input : a = { 3, 2, 5, 2 }
Output : 0
Naive Approach : Check for all possible four elements of the array and then whichever can
form a rectangle. In these rectangles, separate all those rectangles which are of maximum
area formed by these elements. After getting the rectangles and their areas, sum them all
to get our desired solution.
2374
Chapter 382. Sum of Areas of Rectangles possible for an array
Efficient Approach : To get the maximum area rectangle, first sort the elements of the
array in non-increasing array. After sorting, start the procedure to select the elements of
the array. Here, selection of two elements of array (as length of rectangle) is possible if
elements of array are equal (a[i] == a[i+1]) or if length of smaller element a[i+1] is one less
than a[i] (in this case we have our length a[i+1] because a[i] is decreased by 1). One flag
variable is maintained to check that whether we get length and breadth both. After getting
length, set the flag variable, now calculate the breadth in the same way as we have done for
length and sum the area of rectangle. After getting length and breadth both, again set the
flag variable false so that we will now search for a new rectangle. This process is repeated
and lastly, final sum of area is returned.
C++
2375
Chapter 382. Sum of Areas of Rectangles possible for an array
2376
Chapter 382. Sum of Areas of Rectangles possible for an array
// Driver code
int main()
{
int a[] = { 10, 10, 10, 10,
11, 10, 11, 10,
9, 9, 8, 8 };
int n = sizeof(a) / sizeof(a[0]);
cout << MaxTotalRectangleArea(a, n);
return 0;
}
Java
2377
Chapter 382. Sum of Areas of Rectangles possible for an array
2378
Chapter 382. Sum of Areas of Rectangles possible for an array
Python3
2379
Chapter 382. Sum of Areas of Rectangles possible for an array
if(i != 0) :
i = i + 1
# Selecting the length of
# rectangle so that difference
# between any two number is 1
# only. Here length is selected
# so flag is set
if ((a[i] == a[i + 1] or
a[i] - a[i + 1] == 1)
and flag == False) :
# flag is set means
# we have got length of
# rectangle
flag = True
# length is set to
# a[i+1] so that if
# a[i+1] is less than a[i]
# by 1 then also we have
# the correct chice for length
len = a[i + 1]
# incrementing the counter
# one time more as we have
# considered a[i+1] element
# also so.
i = i + 1
# Selecting the width of rectangle
# so that difference between any
# two number is 1 only. Here width
# is selected so now flag is again
# unset for next rectangle
elif ((a[i] == a[i + 1] or
a[i] - a[i + 1] == 1)
and flag == True) :
# area is calculated for
# rectangle
sum = sum + a[i + 1] * len
# flag is set false
# for another rectangle
# which we can get from
# elements in array
flag = False
2380
Chapter 382. Sum of Areas of Rectangles possible for an array
# incrementing the counter
# one time more as we have
# considered a[i+1] element
# also so.
i = i + 1
return sum
# Driver code
a = [ 10, 10, 10, 10, 11, 10,
11, 10, 9, 9, 8, 8 ]
n = len(a)
print (MaxTotalRectangleArea(a, n))
# This code is contributed by
# Manish Shaw (manishshaw1)
C#
2381
Chapter 382. Sum of Areas of Rectangles possible for an array
// Selecting the length of
// rectangle so that difference
// between any two number is 1
// only. Here length is selected
// so flag is set
if ((a[i] == a[i + 1] || a[i] -
a[i + 1] == 1) && (!flag))
{
// flag is set means
// we have got length of
// rectangle
flag = true;
// length is set to
// a[i+1] so that if
// a[i] a[i+1] is less
// than by 1 then also
// we have the correct
// choice for length
len = a[i + 1];
// incrementing the counter
// one time more as we have
// considered a[i+1] element
// also so.
i++;
}
// Selecting the width of rectangle
// so that difference between any
// two number is 1 only. Here width
// is selected so now flag is again
// unset for next rectangle
else if ((a[i] == a[i + 1] ||
a[i] - a[i + 1] == 1) && (flag))
{
// area is calculated for
// rectangle
sum = sum + a[i + 1] * len;
// flag is set false
// for another rectangle
// which we can get from
// elements in array
flag = false;
// incrementing the counter
2382
Chapter 382. Sum of Areas of Rectangles possible for an array
PHP
<?php
// PHP code to find sum
// of all area rectangle
// possible
// Function to find
// area of rectangles
function MaxTotalRectangleArea( $a, $n)
{
// sorting the array in
// descending order
rsort($a);
// store the final sum of
// all the rectangles area
// possible
$sum = 0;
$flag = false;
// temporary variable to store
// the length of rectangle
2383
Chapter 382. Sum of Areas of Rectangles possible for an array
$len;
for ( $i = 0; $i < $n; $i++)
{
// Selecting the length of
// rectangle so that difference
// between any two number is 1
// only. Here length is selected
// so flag is set
if (($a[$i] == $a[$i + 1] or $a[$i] -
$a[$i + 1] == 1) and (!$flag))
{
// flag is set means
// we have got length of
// rectangle
$flag = true;
// length is set to
// a[i+1] so that if
// a[i+1] is less than a[i]
// by 1 then also we have
// the correct chice for length
$len = $a[$i + 1];
// incrementing the counter
// one time more as we have
// considered a[i+1] element
// also so.
$i++;
}
// Selecting the width of rectangle
// so that difference between any
// two number is 1 only. Here width
// is selected so now flag is again
// unset for next rectangle
else if (($a[$i] == $a[$i + 1] or
$a[$i] - $a[$i + 1] == 1) and
($flag))
{
// area is calculated for
// rectangle
$sum = $sum + $a[$i + 1] * $len;
// flag is set false
// for another rectangle
// which we can get from
2384
Chapter 382. Sum of Areas of Rectangles possible for an array
Output :
282
Source
https://www.geeksforgeeks.org/sum-area-rectangles-possible-array/
2385
Chapter 383
Input : n = 4
point1 = { -1, 5 }
point2 = { 1, 6 }
point3 = { 3, 5 }
point4 = { 2, 3 }
Output : 22
Distance of { 1, 6 }, { 3, 5 }, { 2, 3 } from
{ -1, 5 } are 3, 4, 5 respectively.
Therefore, sum = 3 + 4 + 5 = 12
Distance of { 3, 5 }, { 2, 3 } from { 1, 6 }
are 3, 4 respectively.
Therefore, sum = 12 + 3 + 4 = 19
Distance of { 2, 3 } from { 3, 5 } is 3.
Therefore, sum = 19 + 3 = 22.
2386
Chapter 383. Sum of Manhattan distances between all pairs of points
Java
2387
Chapter 383. Sum of Manhattan distances between all pairs of points
// Return the sum of distance between all
// the pair of points.
static int distancesum(int x[], int y[], int n)
{
int sum = 0;
// for each point, finding distance to
// rest of the point
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
sum += (Math.abs(x[i] - x[j]) +
Math.abs(y[i] - y[j]));
return sum;
}
// Driven Program
public static void main(String[] args)
{
int x[] = { -1, 1, 3, 2 };
int y[] = { 5, 6, 5, 3 };
int n = x.length;
System.out.println(distancesum(x, y, n));
}
}
// This code is contributed by vt_m.
Python3
2388
Chapter 383. Sum of Manhattan distances between all pairs of points
# Driven Code
x = [ -1, 1, 3, 2 ]
y = [ 5, 6, 5, 3 ]
n = len(x)
print(distancesum(x, y, n) )
# This code is contributed by "Sharad_Bhardwaj".
C#
PHP
<?php
2389
Chapter 383. Sum of Manhattan distances between all pairs of points
Output:
22
2390
Chapter 383. Sum of Manhattan distances between all pairs of points
and S is the sum of distances from xi to smaller points, then the sum of distances from xj
to smaller points equals S + (xj – xi ) * A.
If we sort all points in non-decreasing order, we can easily compute the desired sum of
distances along one axis between each pair of coordinates in O(N) time, processing points
from left to right and using the above method.
Also, we don’t have to concern if two points are equal coordinates, after sorting points in
non-decreasing order, we say that a point xi is smaller xj if and only if it appears earlier in
the sorted array.
Below is the implementation of this approach:
C++
2391
Chapter 383. Sum of Manhattan distances between all pairs of points
Java
2392
Chapter 383. Sum of Manhattan distances between all pairs of points
Python3
C#
2393
Chapter 383. Sum of Manhattan distances between all pairs of points
PHP
<?php
// PHP Program to find sum of
// Manhattan distances between
// all the pairs of given points
// Return the sum of
// distance of one axis.
function distancesum($arr, $n)
{
// sorting the array.
sort($arr);
2394
Chapter 383. Sum of Manhattan distances between all pairs of points
Output :
22
Source
https://www.geeksforgeeks.org/sum-manhattan-distances-pairs-points/
2395
Chapter 384
Sum of all elements between k1’th and k2’th smallest elements - GeeksforGeeks
Given an array of integers and two numbers k1 and k2. Find sum of all elements between
given two k1’th and k2’th smallest elements of array. It may be assumed that (1 <= k1 <
k2 <= n) and all elements of array are distinct.
Examples :
Method 1 (Sorting)
First sort the given array using a O(n log n) sorting algorithm like Merge Sort, Heap Sort,
etc and return the sum of all element between index k1 and k2 in the sorted array.
Below is the implementation of the above idea :
C++
2396
Chapter 384. Sum of all elements between k1’th and k2’th smallest elements
Java
2397
Chapter 384. Sum of all elements between k1’th and k2’th smallest elements
return result;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 20, 8, 22, 4, 12, 10, 14 };
int k1 = 3, k2 = 6;
int n = arr.length;
System.out.print(sumBetweenTwoKth(arr,
k1, k2));
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
2398
Chapter 384. Sum of all elements between k1’th and k2’th smallest elements
Output:
26
2399
Chapter 384. Sum of all elements between k1’th and k2’th smallest elements
3) Do extract minimum k2 – k1 – 1 times and sum all extracted elements. (This step takes
O ((K2 – k1) * Log n) time)
Overall time complexity of this method is O(n + k2 Log n) which is better than sorting
based method.
Improved By : nitin mittal, AbhishekVats3
Source
https://www.geeksforgeeks.org/sum-elements-k1th-k2th-smallest-elements/
2400
Chapter 385
Naive approach: Using two loops. Pick an element of the array using outer loop and
calculate its absolute difference with rest of the array elements using inner loop. Find the
minimum absolute value and add it to the sum. Time Complexity O(n2 ).
Efficient Approach: The following steps are:
2401
Chapter 385. Sum of minimum absolute difference of each array element
2. For the 1st element of array its min absolute difference is calculated using the 2nd
array element.
3. For the last array element its min absolute difference is calculated using the 2nd last
array element.
4. For the rest of the array elements, 1 <= i <= n-2, minimum absolute difference
for an element at index i is calculated as: minAbsDiff = min( abs(arr[i] – arr[i-1]),
abs(ar[i] – arr[i+1]) ).
C++
2402
Chapter 385. Sum of minimum absolute difference of each array element
Java
2403
Chapter 385. Sum of minimum absolute difference of each array element
Python3
2404
Chapter 385. Sum of minimum absolute difference of each array element
n = len(arr)
print( "Sum = ", sumOfMinAbsDifferences(arr, n))
#This code is contributed by Sam007
C#
2405
Chapter 385. Sum of minimum absolute difference of each array element
PHP
<?php
// PHP implementation to find
// the sum of minimum absolute
// difference of each array element
// function to find the sum of
// minimum absolute difference
function sumOfMinAbsDifferences($arr, $n)
{
// sort the given array
sort($arr);
sort( $arr,$n);
// initialize sum
$sum = 0;
// min absolute difference for
// the 1st array element
$sum += abs($arr[0] - $arr[1]);
// min absolute difference for
// the last array element
$sum += abs($arr[$n - 1] - $arr[$n - 2]);
// find min absolute difference
// for rest of the array elements
// and add them to sum
for ($i = 1; $i < $n - 1; $i++)
$sum += min(abs($arr[$i] - $arr[$i - 1]),
abs($arr[$i] - $arr[$i + 1]));
// required sum
return $sum;
2406
Chapter 385. Sum of minimum absolute difference of each array element
}
// Driver Code
$arr = array(5, 10, 1, 4, 8, 7);
$n = sizeof($arr);
echo "Sum = ", sumOfMinAbsDifferences($arr, $n);
// This code is contributed by nitin mittal.
?>
Output:
Sum = 9
Source
https://www.geeksforgeeks.org/sum-minimum-absolute-difference-array-element/
2407
Chapter 386
• Tag Sort allows sorting an integer array after tagging it with original object.
• In turn, we only swap the tag array integers instead of large array of objects.
• The actual elements are not being changed during the sort process. The positions in
the tag array are being changed so they will hold the correct ordering of the elements
when they are sorted.
In this example, the original elements in arr[] are not changed, but the original elements in
tag[] are manipulated. The tag[] array will now hold the correct subscript ordering of the
elements in arr[] so the array can be sorted into descending order when the tag[] array is
called upon.
2408
Chapter 386. Tag Sort (To get both sorted and original)
Another Example, Suppose we have following Person object which inherently takes large
chunk of memory( in GB or hundreds of MB).
class Person
{
private int id;
private float salary;
private Object someBigObject = new Object();
public Person(int id, float salary)
{ }
public float getSalary()
{ }
public String toString()
{ }
}
Hence, it might not be practical to move around these objects as disk seeks for swaps can
eat up a lot of time. To avoid this, we start by creating a tag array.
• Every Person object is tagged to one element in the tag array and Instead of swapping
the person object for sorting based on salary , we swap the tag[] integers.
• While printing the sorted array we take a cue from the tag array to print the sorted
Persons array.
2409
Chapter 386. Tag Sort (To get both sorted and original)
2410
Chapter 386. Tag Sort (To get both sorted and original)
// Every Person object is tagged to
// an element in the tag array.
System.out.println("Given Person and Tag ");
for (int i = 0; i < n; i++)
System.out.println(persons[i] +
" : Tag: " + tag[i]);
// Modifying tag array so that we can access
// persons in sorted order.
tagSort(persons, tag);
System.out.println("New Tag Array after "+
"getting sorted as per Person[] ");
for (int i=0; i<n; i++)
System.out.println(tag[i]);
// Accessing persons in sorted (by salary)
// way using modified tag array.
for (int i = 0; i < n; i++)
System.out.println(persons[tag[i]]);
}
// Modifying tag array so that we can access
// persons in sorted order of salary.
public static void tagSort(Person persons[],
int tag[])
{
int n = persons.length;
for (int i=0; i<n; i++)
{
for (int j=i+1; j<n; j++)
{
if (persons[tag[i]].getSalary() >
persons[tag[j]].getSalary())
{
// Note we are not sorting the
// actual Persons array, but only
// the tag array
int temp = tag[i];
tag[i] = tag[j];
tag[j] = temp;
}
}
}
}
}
2411
Chapter 386. Tag Sort (To get both sorted and original)
Output:
Source
https://www.geeksforgeeks.org/tag-sort/
2412
Chapter 387
TimSort
TimSort - GeeksforGeeks
TimSort is a sorting algorithm based on Insertion Sort and Merge Sort.
We divides the Array into blocks known as Run. We sort those runs using insertion sort
one by one and then merge those runs using combine function used in merge sort. If size of
Array is less than run, then Array get sorted just by using Insertion Sort. The size of run
may vary from 32 to 64 depending upon size of array. Note that merge function performs
well when sizes subarrays are powers of 2. The idea is based on the fact that insertion sort
performs well for small arrays.
Details of below implementation :
• After sorting individual pieces, we merge them one by one. We double the size of
merged subarrays after every iteration.
2413
Chapter 387. TimSort
2414
Chapter 387. TimSort
// copy remaining elements of left, if any
while (i < len1)
{
arr[k] = left[i];
k++;
i++;
}
// copy remaining element of right, if any
while (j < len2)
{
arr[k] = right[j];
k++;
j++;
}
}
// iterative Timsort function to sort the
// array[0...n-1] (similar to merge sort)
void timSort(int arr[], int n)
{
// Sort individual subarrays of size RUN
for (int i = 0; i < n; i+=RUN)
insertionSort(arr, i, min((i+31), (n-1)));
// start merging from size RUN (or 32). It will merge
// to form size 64, then 128, 256 and so on ....
for (int size = RUN; size < n; size = 2*size)
{
// pick starting point of left sub array. We
// are going to merge arr[left..left+size-1]
// and arr[left+size, left+2*size-1]
// After every merge, we increase left by 2*size
for (int left = 0; left < n; left += 2*size)
{
// find ending point of left sub array
// mid+1 is starting point of right sub array
int mid = left + size - 1;
int right = min((left + 2*size - 1), (n-1));
// merge sub array arr[left.....mid] &
// arr[mid+1....right]
merge(arr, left, mid, right);
}
}
}
2415
Chapter 387. TimSort
Output:
Given Array is
5 21 7 23 19
After Sorting Array is
5 7 19 21 23
References :
https://svn.python.org/projects/python/trunk/Objects/listsort.txt
https://en.wikipedia.org/wiki/Timsort#Minimum_size_.28minrun.29
Source
https://www.geeksforgeeks.org/timsort/
2416
Chapter 388
Algorithm
Time Complexity
Best
Average
Worst
Selection Sort
Ω(n^2)
�(n^2)
O(n^2)
Bubble Sort
Ω(n)
�(n^2)
O(n^2)
Insertion Sort
Ω(n)
�(n^2)
O(n^2)
2417
Chapter 388. Time Complexities of all Sorting Algorithms
Heap Sort
Ω(n log(n))
�(n log(n))
O(n log(n))
Quick Sort
Ω(n log(n))
�(n log(n))
O(n^2)
Merge Sort
Ω(n log(n))
�(n log(n))
O(n log(n))
Bucket Sort
Ω(n+k)
�(n+k)
O(n^2)
Radix Sort
Ω(nk)
�(nk)
O(nk)
Also see:
Source
https://www.geeksforgeeks.org/time-complexities-of-all-sorting-algorithms/
2418
Chapter 389
Time complexity of insertion sort when there are O(n) inversions? - GeeksforGeeks
What is an inversion?
Given an array arr[], a pair arr[i] and arr[j] forms an inversion if arr[i] < arr[j] and i > j. For
example, the array {1, 3, 2, 5} has one inversion (3, 2) and array {5, 4, 3} has inversions (5,
4), (5, 3) and (4, 3). We have discussed a merge sort based algorithm to count inversions
What is the time complexity of Insertion Sort when there are O(n) inversions?
Consider the following function of insertion sort.
2419
Chapter 389. Time complexity of insertion sort when there are O(n) inversions?
}
}
If we take a closer look at the insertion sort code, we can notice that every iteration of
while loop reduces one inversion. The while loop executes only if i > j and arr[i] < arr[j].
Therefore total number of while loop iterations (For all values of i) is same as number of
inversions. Therefore overall time complexity of the insertion sort is O(n + f(n)) where f(n)
is inversion count. If the inversion count is O(n), then the time complexity of insertion sort
is O(n). In worst case, there can be n*(n-1)/2 inversions. The worst case occurs when the
array is sorted in reverse order. So the worst case time complexity of insertion sort is O(n2 ).
Source
https://www.geeksforgeeks.org/time-complexity-insertion-sort-inversions/
2420
Chapter 390
Tree Sort
C++
2421
Chapter 390. Tree Sort
2422
Chapter 390. Tree Sort
// Driver Program to test above functions
int main()
{
//create input array
int arr[] = {5, 4, 7, 2, 11};
int n = sizeof(arr)/sizeof(arr[0]);
treeSort(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Java
2423
Chapter 390. Tree Sort
2424
Chapter 390. Tree Sort
}
// Driver Code
public static void main(String[] args)
{
GFG tree = new GFG();
int arr[] = {5, 4, 7, 2, 11};
tree.treeins(arr);
tree.inorderRec(tree.root);
}
}
// This code is contributed
// by Vibin M
Output:
2 4 5 7 11
Average Case Time Complexity : O(n log n) Adding one item to a Binary Search tree
on average takes O(log n) time. Therefore, adding n items will take O(n log n) time
Worst Case Time Complexity : O(n2 ). The worst case time complexity of Tree Sort
can be improved by using a self-balancing binary search tree like Red Black Tree, AVL Tree.
Using self-balancing binary tree Tree Sort will take O(n log n) time to sort the array in
worst case.
Auxiliary Space : O(n)
References:
https://en.wikipedia.org/wiki/Tree_sort
Improved By : vibi, vsushko
Source
https://www.geeksforgeeks.org/tree-sort/
2425
Chapter 391
Input : A[] = { 1, 1, 2, 2, 3 }, k = 1
Output : 5
(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3),
(2, 3, 4) are the triplet whose element will
satisfy the above three condition.
Input : A[] = { 1, 2, 3 }, k = 1
Output : 1
A simple solution is to run three nested loops and count triplets with given constraints.
An efficient solution is based on the fact rearranging the elements in the array does not
affect the answer because basically, we want index x, y, z to be in increasing order, not A[x],
A[y], A[z] to be sorted. Suppose, A[x] is at index y, A[y] at z, A[z] at x, still we can pick
the triplet (x, y, z) because the condition of difference between any two elements to be less
k still stands.
Now, to calculate the number of triplet indices (x, y, z) which satisfies the above condition,
we will sort the given array. Now, for each element A[i], i >= 2, we will find the lower bound
index of A[i] – k, say lb. Now, observe all the element between index lb and i are less than
2426
Chapter 391. Triplets in array with absolute difference less than k
A[i] and the difference between any teo elements will be less than or equal to k. So, element
at index i can be treated as index z and we can choose any two element from lb to i – 1. So,
this will increase the count of the triplet by i – lb C2 .
Below is the implementation of this approach:
C++
2427
Chapter 391. Triplets in array with absolute difference less than k
Java
2428
Chapter 391. Triplets in array with absolute difference less than k
{
end = mid - 1;
ans = mid;
}
else
{
start = mid + 1;
}
}
return ans;
}
// Return the number of
// triplet indices satisfies
// the three constraints
static int countTriplet(int arr[],
int n, int k)
{
int count = 0;
// sort the array
Arrays.sort(arr);
// for each element from
// index 2 to n - 1.
for (int i = 2; i < n; i++)
{
// finding the lower
// bound of arr[i] - k.
int cur = binary_lower(arr[i] - k,
arr, n);
// If there are at least two
// elements between lower
// bound and current element.
if (cur <= i - 2)
{
// increment the count
// by lb - i C 2.
count += ((i - cur) *
(i - cur - 1)) / 2;
}
}
return count;
}
2429
Chapter 391. Triplets in array with absolute difference less than k
// Driver Code
public static void main (String[] args)
{
int arr[] = {1, 1, 2, 2, 3};
int k = 1;
int n = arr.length;
System.out.println(countTriplet(arr, n, k));
}
}
// This code is contributed by anuj_67.
C#
2430
Chapter 391. Triplets in array with absolute difference less than k
return ans;
}
// Return the number of
// triplet indices satisfies
// the three constraints
static int countTriplet(int []arr,
int n, int k)
{
int count = 0;
// sort the array
Array.Sort(arr);
// for each element from
// index 2 to n - 1.
for (int i = 2; i < n; i++)
{
// finding the lower
// bound of arr[i] - k.
int cur = binary_lower(arr[i] - k,
arr, n);
// If there are at least two
// elements between lower
// bound and current element.
if (cur <= i - 2)
{
// increment the count
// by lb - i C 2.
count += ((i - cur) *
(i - cur - 1)) / 2;
}
}
return count;
}
// Driver Code
public static void Main ()
{
int []arr = {1, 1, 2, 2, 3};
int k = 1;
int n = arr.Length;
Console.WriteLine(countTriplet(arr, n, k));
}
2431
Chapter 391. Triplets in array with absolute difference less than k
}
// This code is contributed by anuj_67.
Output:
Complexity: O(nlogn)
Improved By : vt_m
Source
https://www.geeksforgeeks.org/triplets-array-absolute-difference-less-k/
2432
Chapter 392
Input:
List1: 10->15->4->20
lsit2: 8->4->2->10
Output:
Intersection List: 4->10
Union List: 2->8->20->4->15->10
Method 1 (Simple)
Following are simple algorithms to get union and intersection lists respectively.
Intersection (list1, list2)
Initialize result list as NULL. Traverse list1 and look for its each element in list2, if the
element is present in list2, then add the element to result.
Union (list1, list2):
Initialize result list as NULL. Traverse list1 and add all of its elements to the result.
Traverse list2. If an element of list2 is already present in result then do not insert it to
result, otherwise insert.
This method assumes that there are no duplicates in the given lists.
Thanks to Shekhu for suggesting this method. Following are C and Java implementations
of this method.
C/C++
2433
Chapter 392. Union and Intersection of two Linked Lists
2434
Chapter 392. Union and Intersection of two Linked Lists
{
struct Node *result = NULL;
struct Node *t1 = head1;
// Traverse list1 and search each element of it in
// list2. If the element is present in list 2, then
// insert the element to result
while (t1 != NULL)
{
if (isPresent(head2, t1->data))
push (&result, t1->data);
t1 = t1->next;
}
return result;
}
/* A utility function to insert a node at the begining of a linked list*/
void push (struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* A utility function to print a linked list*/
void printList (struct Node *node)
{
while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
}
/* A utility function that returns true if data is
present in linked list else return false */
bool isPresent (struct Node *head, int data)
{
2435
Chapter 392. Union and Intersection of two Linked Lists
2436
Chapter 392. Union and Intersection of two Linked Lists
Java
2437
Chapter 392. Union and Intersection of two Linked Lists
2438
Chapter 392. Union and Intersection of two Linked Lists
return false;
}
/* Drier program to test above functions */
public static void main(String args[])
{
LinkedList llist1 = new LinkedList();
LinkedList llist2 = new LinkedList();
LinkedList unin = new LinkedList();
LinkedList intersecn = new LinkedList();
/*create a linked lits 10->15->5->20 */
llist1.push(20);
llist1.push(4);
llist1.push(15);
llist1.push(10);
/*create a linked lits 8->4->2->10 */
llist2.push(10);
llist2.push(2);
llist2.push(4);
llist2.push(8);
intersecn.getIntersection(llist1.head, llist2.head);
unin.getUnion(llist1.head, llist2.head);
System.out.println("First List is");
llist1.printList();
System.out.println("Second List is");
llist2.printList();
System.out.println("Intersection List is");
intersecn.printList();
System.out.println("Union List is");
unin.printList();
}
} /* This code is contributed by Rajat Mishra */
Output:
First list is
10 15 4 20
Second list is
8 4 2 10
2439
Chapter 392. Union and Intersection of two Linked Lists
Intersection list is
4 10
Union list is
2 8 20 4 15 10
Time Complexity: O(mn) for both union and intersection operations. Here m is the number
of elements in first list and n is the number of elements in second list.
Method 2 (Use Merge Sort)
In this method, algorithms for Union and Intersection are very similar. First we sort the
given lists, then we traverse the sorted lists to get union and intersection.
Following are the steps to be followed to get union and intersection lists.
1) Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this
post for details of this step.
2) Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this
post for details of this step.
3) Linearly scan both sorted lists to get the union and intersection. This step takes O(m +
n) time. This step can be implemented using the same algorithm as sorted arrays algorithm
discussed here.
Time complexity of this method is O(mLogm + nLogn) which is better than method 1’s
time complexity.
Method 3 (Use Hashing)
Union (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse both lists one
by one, for each element being visited, look the element in hash table. If the element is not
present, then insert the element to result list. If the element is present, then ignore it.
Intersection (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse list1. For each
element being visited in list1, insert the element in hash table. Traverse list2, for each
element being visited in list2, look the element in hash table. If the element is present, then
insert the element to result list. If the element is not present, then ignore it.
Both of the above methods assume that there are no duplicates.
2440
Chapter 392. Union and Intersection of two Linked Lists
Node(int d)
{
data = d;
next = null;
}
}
/* Utility function to print list */
void printList()
{
Node temp = head;
while(temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
/* Inserts a node at start of linked list */
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
public void append(int new_data)
{
if(this.head == null)
{
Node n = new Node(new_data);
this.head = n;
return;
}
Node n1 = this.head;
Node n2 = new Node(new_data);
while(n1.next != null)
{
n1 = n1.next;
}
2441
Chapter 392. Union and Intersection of two Linked Lists
n1.next = n2;
n2.next = null;
}
/* A utilty function that returns true if data is
present in linked list else return false */
boolean isPresent (Node head, int data)
{
Node t = head;
while (t != null)
{
if (t.data == data)
return true;
t = t.next;
}
return false;
}
LinkedList getIntersection(Node head1, Node head2)
{
HashSet<Integer> hset = new HashSet<>();
Node n1 = head1;
Node n2 = head2;
LinkedList result = new LinkedList();
// loop stores all the elements of list1 in hset
while(n1 != null)
{
if(hset.contains(n1.data))
{
hset.add(n1.data);
}
else
{
hset.add(n1.data);
}
n1 = n1.next;
}
//For every element of list2 present in hset
//loop inserts the element into the result
while(n2 != null)
{
if(hset.contains(n2.data))
{
result.push(n2.data);
}
n2 = n2.next;
2442
Chapter 392. Union and Intersection of two Linked Lists
}
return result;
}
LinkedList getUnion(Node head1, Node head2)
{
// HashMap that will store the
// elements of the lists with their counts
HashMap<Integer, Integer> hmap = new HashMap<>();
Node n1 = head1;
Node n2 = head2;
LinkedList result = new LinkedList();
// loop inserts the elements and the count of
// that element of list1 into the hmap
while(n1 != null)
{
if(hmap.containsKey(n1.data))
{
int val = hmap.get(n1.data);
hmap.put(n1.data, val + 1);
}
else
{
hmap.put(n1.data, 1);
}
n1 = n1.next;
}
// loop further adds the elements of list2 with
// their counts into the hmap
while(n2 != null)
{
if(hmap.containsKey(n2.data))
{
int val = hmap.get(n2.data);
hmap.put(n2.data, val + 1);
}
else
{
hmap.put(n2.data, 1);
}
n2 = n2.next;
}
// Eventually add all the elements
// into the result that are present in the hmap
for(int a:hmap.keySet())
2443
Chapter 392. Union and Intersection of two Linked Lists
{
result.append(a);
}
return result;
}
/* Driver program to test above functions */
public static void main(String args[])
{
LinkedList llist1 = new LinkedList();
LinkedList llist2 = new LinkedList();
LinkedList union = new LinkedList();
LinkedList intersection = new LinkedList();
/*create a linked list 10->15->4->20 */
llist1.push(20);
llist1.push(4);
llist1.push(15);
llist1.push(10);
/*create a linked list 8->4->2->10 */
llist2.push(10);
llist2.push(2);
llist2.push(4);
llist2.push(8);
intersection = intersection.getIntersection(llist1.head,
llist2.head);
union=union.getUnion(llist1.head, llist2.head);
System.out.println("First List is");
llist1.printList();
System.out.println("Second List is");
llist2.printList();
System.out.println("Intersection List is");
intersection.printList();
System.out.println("Union List is");
union.printList();
}
}
// This code is contributed by Kamal Rawal
Output:
2444
Chapter 392. Union and Intersection of two Linked Lists
First List is
10 15 4 20
Second List is
8 4 2 10
Intersection List is
10 4
Union List is
2 4 20 8 10 15
Time complexity of this method depends on the hashing technique used and the distribution
of elements in input lists. In practical, this approach may turn out to be better than above
2 methods.
Source
https://www.geeksforgeeks.org/union-and-intersection-of-two-linked-lists/
2445
Chapter 393
Union and Intersection of two linked lists Set-2 (Using Merge Sort) - GeeksforGeeks
Given two Linked Lists, create union and intersection lists that contain union and inter-
section of the elements present in the given lists. Order of elements in output lists doesn’t
matter.
Examples:
Input:
List1: 10 -> 15 -> 4 ->20
lsit2: 8 -> 4 -> 2 -> 10
Output:
Intersection List: 4 -> 10
Union List: 2 -> 8 -> 20 -> 4 -> 15 -> 10
There were three methods discussed in this post with an implementation of Method 1.
In this post, we will see an implementation of Method 2 i.e. Using Merge sort.
Implementation:
Following are the steps to be followed to get union and intersection lists.
2) Linearly scan both sorted lists to get the union and intersection.
This step takes O(m + n) time.
2446
Chapter 393. Union and Intersection of two linked lists Set-2 (Using Merge Sort)
Just like Method 1, This method also assumes that there are distinct elements in the lists.
2447
Chapter 393. Union and Intersection of two linked lists Set-2 (Using Merge Sort)
else
{
slow = source;
fast = source->next;
/* Advance 'fast' two nodes, and advance 'slow' one node */
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
/* 'slow' is before the midpoint in the list,
so split it in two at that point. */
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
}
/* See https://www.geeksforgeeks.org/?p=3622 for details
of this function */
struct Node* SortedMerge(struct Node* a, struct Node* b)
{
struct Node* result = NULL;
/* Base cases */
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
/* Pick either a or b, and recur */
if (a->data <= b->data)
{
result = a;
result->next = SortedMerge(a->next, b);
}
else
{
result = b;
result->next = SortedMerge(a, b->next);
}
return(result);
2448
Chapter 393. Union and Intersection of two linked lists Set-2 (Using Merge Sort)
}
/* sorts the linked list by changing next pointers
(not data) */
void mergeSort(struct Node** headRef)
{
struct Node *head = *headRef;
struct Node *a, *b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL))
return;
/* Split head into 'a' and 'b' sublists */
FrontBackSplit(head, &a, &b);
/* Recursively sort the sublists */
mergeSort(&a);
mergeSort(&b);
/* answer = merge the two sorted lists together */
*headRef = SortedMerge(a, b);
}
/* Function to get union of two linked lists head1 and head2 */
struct Node *getUnion(struct Node *head1, struct Node *head2)
{
struct Node *result = NULL;
struct Node *t1 = head1, *t2 = head2;
// Traverse both lists and store the element in
// the resu1tant list
while (t1 != NULL && t2 != NULL)
{
// Move to the next of first list
// if its element is smaller
if (t1->data < t2->data)
{
push(&result, t1->data);
t1 = t1->next;
}
// Else move to the next of second list
else if (t1->data>t2->data)
{
push(&result, t2->data);
t2 = t2->next;
2449
Chapter 393. Union and Intersection of two linked lists Set-2 (Using Merge Sort)
}
// If same then move to the next node
// in both lists
else
{
push(&result, t2->data);
t1 = t1->next;
t2 = t2->next;
}
}
/* Print remaining elements of the lists */
while (t1 != NULL)
{
push(&result, t1->data);
t1 = t1->next;
}
while (t2 != NULL)
{
push(&result, t2->data);
t2 = t2->next;
}
return result;
}
/* Function to get intersection of two linked lists
head1 and head2 */
struct Node *getIntersection(struct Node *head1,
struct Node *head2)
{
struct Node *result = NULL;
struct Node *t1 = head1, *t2 = head2;
// Traverse both lists and store the same element
// in the resu1tant list
while (t1 != NULL && t2 != NULL)
{
// Move to the next of first list if smaller
if (t1->data < t2->data)
t1 = t1->next;
// Move to the next of second list if it is smaller
else if (t1->data > t2->data)
t2 = t2->next;
// If both are same
2450
Chapter 393. Union and Intersection of two linked lists Set-2 (Using Merge Sort)
else
{
// Store current element in the list
push(&result, t2->data);
// Move to the next node of both lists
t1 = t1->next;
t2 = t2->next;
}
}
//return the resultant list
return result;
}
/* A utility function to print a linked list*/
void printList (struct Node *node)
{
while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head1 = NULL;
struct Node* head2 = NULL;
struct Node* intersection_list = NULL;
struct Node* union_list = NULL;
/*create a linked lits 11->10->15->4->20 */
push(&head1, 20);
push(&head1, 4);
push(&head1, 15);
push(&head1, 10);
push(&head1, 11);
/*create a linked lits 8->4->2->10 */
push(&head2, 10);
push(&head2, 2);
push(&head2, 4);
push(&head2, 8);
2451
Chapter 393. Union and Intersection of two linked lists Set-2 (Using Merge Sort)
Output:
First list is
4 10 11 15 20
Second list is
2 4 8 10
Intersection list is
10 4
Union list is
20 15 11 10 8 4 2
Source
https://www.geeksforgeeks.org/union-intersection-two-linked-lists-set-2-using-merge-sort/
2452
Chapter 394
Input:
List1: 10 -> 15 -> 4 -> 20
list2: 8 -> 4 -> 2 -> 10
Output:
Intersection List: 4 -> 10
Union List: 2 -> 8 -> 20 -> 4 -> 15 -> 10
Implementation:
1- Start traversing both the lists.
a) Store the current element of both lists
with its occurrence in the map.
2- For Union: Store all the elements of the map
in the resultant list.
3- For Intersection: Store all the elements only
with an occurrence of 2 as 2 denotes that
they are present in both the lists.
2453
Chapter 394. Union and Intersection of two linked lists Set-3 (Hashing)
2454
Chapter 394. Union and Intersection of two linked lists Set-3 (Hashing)
// store element in the map
if (ptr2 != NULL)
{
eleOcc[ptr2->data]++;
ptr2=ptr2->next;
}
}
}
/* Function to get union of two linked lists head1
and head2 */
struct Node *getUnion(unordered_map<int, int> eleOcc)
{
struct Node *result = NULL;
// Push all the elements into the resultant list
for (auto it=eleOcc.begin(); it!=eleOcc.end(); it++)
push(&result, it->first);
return result;
}
/* Function to get intersection of two linked lists
head1 and head2 */
struct Node *getIntersection(unordered_map<int, int> eleOcc)
{
struct Node *result = NULL;
// Push a node with an element having occurrence
// of 2 as that means the current element is present
// in both the lists
for (auto it=eleOcc.begin(); it!=eleOcc.end(); it++)
if (it->second == 2)
push(&result, it->first);
// return resultant list
return result;
}
/* A utility function to print a linked list*/
void printList(struct Node *node)
{
while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
2455
Chapter 394. Union and Intersection of two linked lists Set-3 (Hashing)
}
// Prints union and intersection of lists with head1
// and head2.
void printUnionIntersection(Node *head1, Node *head2)
{
// Store all the elements of both lists in the map
unordered_map<int, int> eleOcc;
storeEle(head1, head2, eleOcc);
Node *intersection_list = getIntersection(eleOcc);
Node *union_list = getUnion(eleOcc);
printf("\nIntersection list is \n");
printList(intersection_list);
printf("\nUnion list is \n");
printList(union_list);
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head1 = NULL;
struct Node* head2 = NULL;
/* create a linked lits 11->10->15->4->20 */
push(&head1, 1);
push(&head1, 2);
push(&head1, 3);
push(&head1, 4);
push(&head1, 5);
/* create a linked lits 8->4->2->10 */
push(&head2, 1);
push(&head2, 3);
push(&head2, 5);
push(&head2, 6);
printf("First list is \n");
printList(head1);
printf("\nSecond list is \n");
printList(head2);
printUnionIntersection(head1, head2);
2456
Chapter 394. Union and Intersection of two linked lists Set-3 (Hashing)
return 0;
}
Output:
First list is
5 4 3 2 1
Second list is
6 5 3 1
Intersection list is
3 5 1
Union list is
3 4 6 5 2 1
We can also handle the case of duplicates by maintaining separate Hash for both the lists.
Time Complexity : O(m + n)
Auxiliary Space : O(m + n)
Source
https://www.geeksforgeeks.org/union-intersection-two-linked-lists-set-3-hashing/
2457
Chapter 395
Examples:
Approach:
This problem uses greedy technique.
2458
Chapter 395. Water drop problem
A drop will mix with another drop if two conditions are met:
1. If the drop is faster than the drop it is mixing with
2. If the position of the faster drop is behind the slower drop.
We use an array of pairs to store the position and the time that ith drop would take to reach
the end of the pipe. Then we sort the array according to the position of the drops. Now
we have a fair idea of which drops lie behind which drops and their respective time taken
to reach the end.More time means less speed and less time means more speed. Now all the
drops before a slower drop will mix with it. And all the drops after the slower drop with
mix with the next slower drop and so on.
For example if the times to reach the end are- 12, 3, 7, 8, 1 (sorted according to positions)
0th drop is slowest, it won’t mix with the next drop
1st drop is faster than the 2nd drop so they will mix and 2nd drop is faster than 3rd drop
so all three will mix together. They cannot mix with the 4th drop because that is faster.
So we use a stack to maintain the local maxima of the times.
No of local maximal + residue(drops after last local maxima) = total no of drops
#include <bits/stdc++.h>
using namespace std;
int drops(int length, int position[], int speed[], int n)
{
// stores position and time taken by a single
// drop to reach the end as a pair
vector<pair<int, double> > m(n);
int i;
for (i = 0; i < n; i++) {
// calculates distance needs to be
// covered by the ith drop
int p = length - position[i];
// inserts initial position of the
// ith drop to the pair
m[i].first = position[i];
// inserts time taken by ith drop to reach
// the end to the pair
m[i].second = p * 1.0 / speed[i];
}
// sorts the pair according to increasing
// order of their positions
sort(m.begin(), m.end());
int k = 0; // counter for no of final drops
// stack to maintain the next slower drop
// which might coalesce with the current drop
stack<double> s;
2459
Chapter 395. Water drop problem
// we traverse the array demo right to left
// to determine the slower drop
for (i = n - 1; i >= 0; i--)
{
if (s.empty()) {
s.push(m[i].second);
}
// checks for next slower drop
if (m[i].second > s.top())
{
s.pop();
k++;
s.push(m[i].second);
}
}
// calculating residual drops in the pipe
if (!s.empty())
{
s.pop();
k++;
}
return k;
}
// driver function
int main()
{
int length = 12; // length of pipe
int position[] = { 10, 8, 0, 5, 3 }; // position of droplets
int speed[] = { 2, 4, 1, 1, 3 }; // speed of each droplets
int n = sizeof(speed)/sizeof(speed[0]);
cout << drops(length, position, speed, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/water-drop-problem/
2460
Chapter 396
This article aims at performing this functionality using itemgetter and showing visible dif-
ferences.
Itemgetter can be used instead of lambda function to achieve the similar functionality. Out-
puts in same way as sorted() and lambda, but has different internal implementation. It
takes keys of dictionaries and converts them into tuples. It reduces overhead and is faster
and more efficient. The “operator” module has to be imported for its working. The code
is explained below
2461
Chapter 396. Ways to sort list of dictionaries by values in Python – Using itemgetter
Output:
• Concise : : itemgetter looks more concise when accessing multiple values than lambda
functions.
Source
https://www.geeksforgeeks.org/ways-sort-list-dictionaries-values-python-using-itemgetter/
2462
Chapter 397
Source
https://www.geeksforgeeks.org/when-does-the-worst-case-of-quicksort-occur/
2463
Chapter 398
Source
https://www.geeksforgeeks.org/where-is-heap-sort-used-practically/
2464
Chapter 399
Source
https://www.geeksforgeeks.org/which-sorting-algorithm-makes-minimum-number-of-writes/
2465
Chapter 400
Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists? - GeeksforGeeks
Why is Quick Sortpreferred for arrays?
Below are recursive and iterative implementations of Quick Sort and Merge Sort for arrays.
Recursive Quick Sort for array.
Iterative Quick Sort for arrays.
Recursive Merge Sort for arrays
Iterative Merge Sort for arrays
• Quick Sort in its general form is an in-place sort (i.e. it doesn’t require any extra
storage) whereas merge sort requires O(N) extra storage, N denoting the array size
which may be quite expensive. Allocating and de-allocating the extra space used for
merge sort increases the running time of the algorithm.
• Comparing average complexity we find that both type of sorts have O(NlogN) average
complexity but the constants differ. For arrays, merge sort loses due to the use of
extra O(N) storage space.
• Most practical implementations of Quick Sort use randomized version. The random-
ized version has expected time complexity of O(nLogn). The worst case is possible in
randomized version also, but worst case doesn’t occur for a particular pattern (like
sorted array) and randomized Quick Sort works well in practice.
• Quick Sort is also a cache friendly sorting algorithm as it has good locality of reference
when used for arrays.
• Quick Sort is also tail recursive, therefore tail call optimizations is done.
2466
Chapter 400. Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
• In case of linked lists the case is different mainly due to difference in memory allocation
of arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in
memory.
• Unlike array, in linked list, we can insert items in the middle in O(1) extra space
and O(1) time. Therefore merge operation of merge sort can be implemented without
extra space for linked lists.
• In arrays, we can do random access as elements are continuous in memory. Let us say
we have an integer (4-byte) array A and let the address of A[0] be x then to access
A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can not do
random access in linked list.
• Quick Sort requires a lot of this kind of access. In linked list to access i’th index,
we have to travel each and every node from the head to i’th node as we don’t have
continuous block of memory. Therefore, the overhead increases for quick sort. Merge
sort accesses data sequentially and the need of random access is low.
Related Articles:
Thanks to Sayan Mukhopadhyay for providing initial draft for above article. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above.
Source
https://www.geeksforgeeks.org/why-quick-sort-preferred-for-arrays-and-merge-sort-for-linked-lists/
2467
Chapter 401
2468
Chapter 401. Why is it faster to process sorted array than an unsorted array ?
Output :
Execution 1:
Time for unsorted array :: 0.00108
Time for sorted array :: 0.00053
Execution 2:
Time for unsorted array :: 0.001101
Time for sorted array :: 0.000593
Execution 3:
Time for unsorted array :: 0.0011
Time for sorted array :: 0.000418
Observe that time taken for processing a sorted array is less as compared to unsorted array.
The reason for this optimisation for sorted array is branch prediction.
What is branch prediction ?
In computer architecture, branch prediction means determining whether a conditional
branch(jump) in the instruction flow of a program is likely to be taken or not.
All the pipelined processors do branch prediction in some form, because they must guess the
address of the next instruction to fetch before the current instruction has been executed.
2469
Chapter 401. Why is it faster to process sorted array than an unsorted array ?
T = if condition true
F = if condition false
arr[] = {0,1,2,3,4,5,6, .... , 4999,5000,5001, ... , 100000}
{T,T,T,T,T,T,T, .... , T, F, F, ... , F }
We can observe that it is very easy to predict the branch in sorted array, as the sequence is
TTTTTTTTTTTT………FFFFFFFFFFFFF
Case 2 : Unsorted array
T = if condition true
F = if condition false
arr[] = {5,0,5000,10000,17,13, ... , 3,21000,10}
{T,T,F, F, T, T, ... , T, F, T}
It is very difficult to predict that if statement will be false or true, hence branch prediction
don’t play any significant role here.
Branch prediction works on the pattern the algorithm is following or basically the history,
how it got executed in previous steps. If the guess is correct, then CPU continue executing
and if it goes wrong, then CPU need to flush the pipeline and roll back to the branch and
restart from beginning.
In case compiler is not able to utilise branch prediction as a tool for improving performance,
programmer can implement his own hacks to improve performance.
References :
• Branch_prediction
• StackOverflow
• Pipelining in computing
Source
https://www.geeksforgeeks.org/faster-process-sorted-array-unsorted-array/
2470
Chapter 402
1. Auxiliary Space : Mergesort uses extra space, quicksort requires little space and
exhibits good cache locality. Quick sort is an in-place sorting algorithm. In-place
sorting means no additional storage space is needed to perform sorting. Merge sort
requires a temporary array to merge the sorted arrays and hence it is not in-place
giving Quick sort the advantage of space.
2. Worst Cases : The worst case of quicksort O(n2 ) can be avoided by using random-
ized quicksort. It can be easily avoided with high probability by choosing the right
pivot. Obtaining an average case behavior by choosing right pivot element makes it
improvise the performance and becoming as efficient as Merge sort.
3. Locality of reference : Quicksort in particular exhibits good cache locality and this
makes it faster than merge sort in many cases like in virtual memory environment.
4. Merge sort is better for large data structures: Mergesort is a stable sort, unlike
quicksort and heapsort, and can be easily adapted to operate on linked lists and very
large lists stored on slow-to-access media such as disk storage or network attached
storage. Refer this for details
The std::sort() function which is present in C++ STL is a hybrid sorting algorithm provides
average and worst case time complexity of O(nlogn). The sorting algorithm which it uses
is called Introsort.
Introsort is combination of both quicksort and heapsort, It begins with quicksort and
switch to heapsort if recursion depth exceeds a level based on the number of elements being
sorted.
2471
Chapter 402. Why quicksort is better than mergesort ?
Related Article: Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
Source
https://www.geeksforgeeks.org/quicksort-better-mergesort/
2472
Chapter 403
2473
Chapter 403. k largest(or smallest) elements in an array added Min Heap method
Java
2474
Chapter 403. k largest(or smallest) elements in an array added Min Heap method
// Print the first kth largest elements
for (int i = 0; i < k; i++)
System.out.print(arr[i] + " ");
}
public static void main(String[] args)
{
Integer arr[] = new Integer[]{1, 23, 12, 9,
30, 2, 50};
int k = 3;
kLargest(arr,k);
}
}
// This code is contributed by Kamal Rawal
Python
Output:
50 30 23
2475
Chapter 403. k largest(or smallest) elements in an array added Min Heap method
Source
https://www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/
2476
Chapter 404
We have discussed efficient solution to find n smallest elements of above problem with using
extra space of O(n). To solve it without using any extra space we will use concept of
insertion sort.
The idea is to move k minimum elements to beginning in same order. To do this, we start
from (k+1)-th element and move till end. For every array element, we replace the largest
element of first k elements with the current element if current element is smaller than the
largest. To keep the order, we use insertion sort idea.
C++
2477
Chapter 404. k smallest elements in same order using O(1) extra space
2478
Chapter 404. k smallest elements in same order using O(1) extra space
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 5;
printSmall(arr, n, k);
return 0;
}
Java
2479
Chapter 404. k smallest elements in same order using O(1) extra space
}
// Driver function
public static void main(String argc[])
{
int[] arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = 10;
int k = 5;
printSmall(arr, n, k);
}
}
/* This code is contributed by Sagar Shukla */
Python3
2480
Chapter 404. k smallest elements in same order using O(1) extra space
j += 1
# make arr[k-1] = arr[i]
arr[k - 1] = arr[i]
# print result
for i in range(0, k):
print(arr[i], end = " ")
# Driver program
arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]
n = len(arr)
k = 5
printSmall(arr, n, k)
# This code is contributed by
# Smitha Dinesh Semwal
C#
2481
Chapter 404. k smallest elements in same order using O(1) extra space
}
}
// If largest is greater than arr[i]
// shift all element one place left
if (max_var > arr[i]) {
int j = pos;
while (j < k - 1) {
arr[j] = arr[j + 1];
j++;
}
// make arr[k-1] = arr[i]
arr[k - 1] = arr[i];
}
}
// print result
for (int i = 0; i < k; i++)
Console.Write(arr[i] + " ");
}
// Driver function
public static void Main()
{
int[] arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = 10;
int k = 5;
printSmall(arr, n, k);
}
}
/* This code is contributed by Vt_m */
PHP
<?php
// PHP for printing smallest
// k numbers in order
// Function to print smallest k
// numbers in arr[0..n-1]
function printSmall($arr, $n, $k)
{
// For each arr[i] find whether
2482
Chapter 404. k smallest elements in same order using O(1) extra space
2483
Chapter 404. k smallest elements in same order using O(1) extra space
Output :
1 3 4 2 0
Improved By : vt_m
Source
https://www.geeksforgeeks.org/k-smallest-elements-order-using-o1-extra-space/
2484
Chapter 405
sort() in Python
List_name.sort()
This will sort the given list in ascending order.
This function can be used to sort list of integers, floating point number, string and others.
# List of Integers
numbers = [1, 3, 4, 2]
# Sorting list of Integers
numbers.sort()
print(numbers)
# List of Floating point numbers
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]
# Sorting list of Floating point numbers
decimalnumber.sort()
print(decimalnumber)
2485
Chapter 405. sort() in Python
# List of strings
words = ["Geeks", "For", "Geeks"]
# Sorting list of strings
words.sort()
print(words)
Output:
[1, 2, 3, 4]
[1.68, 2.0, 2.01, 3.28, 3.67]
['For', 'Geeks', 'Geeks']
list_name.sort(reverse=True)
This will sort the given list in descending order.
# List of Integers
numbers = [1, 3, 4, 2]
# Sorting list of Integers
numbers.sort(reverse=True)
print(numbers)
# List of Floating point numbers
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]
# Sorting list of Floating point numbers
decimalnumber.sort(reverse=True)
print(decimalnumber)
# List of strings
words = ["Geeks", "For", "Geeks"]
# Sorting list of strings
words.sort(reverse=True)
print(words)
Output:
2486
Chapter 405. sort() in Python
[4, 3, 2, 1]
[3.67, 3.28, 2.01, 2.0, 1.68]
['Geeks', 'Geeks', 'For']
Syntax :
Parameters:
By default, sort() doesn’t require any extra parameters. However, it has two optional
parameters:
Return value:
Output:
2487
Chapter 405. sort() in Python
Source
https://www.geeksforgeeks.org/sort-in-python/
2488
Chapter 406
Output :
2489
Chapter 406. stable_sort() in C++ STL
Output:
2490
Chapter 406. stable_sort() in C++ STL
Output:
Implementation
sort() function usually uses Introsort. Therefore, sort() may preserve the physical order of
semantically equivalent values but can’t be guaranteed.
stable_sort() function usually uses mergesort. Therefore, stable_sort() preserve the physical
order of semantically equivalent values and its guaranteed.
Time Complexity
For sort() it is O(n*log(n))
For stable_sort() it is O(n*log^2(n)) if additional memory linearly proportional to length
is not available. If its available then O(n*log(n)).
2491
Chapter 406. stable_sort() in C++ STL
Source
https://www.geeksforgeeks.org/stable_sort-c-stl/
2492
Chapter 407
Output :
2493
Chapter 407. std::sort() in C++ STL
Output:
2494
Chapter 407. std::sort() in C++ STL
{
return (i1.start < i2.start);
}
int main()
{
Interval arr[] = { {6,8}, {1,9}, {2,4}, {4,7} };
int n = sizeof(arr)/sizeof(arr[0]);
// sort the intervals in increasing order of
// start time
sort(arr, arr+n, compareInterval);
cout << "Intervals sorted by start time : \n";
for (int i=0; i<n; i++)
cout << "[" << arr[i].start << "," << arr[i].end
<< "] ";
return 0;
}
Output:
This article is contributed by Shubham Agrawal. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Improved By : rahuku
Source
https://www.geeksforgeeks.org/sort-c-stl/
2495