Basic Sorting Algorithms
Basic Sorting Algorithms
Basic Sorting
Algorithms
What is Sorting?
A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison operator
on the elements. The comparison operator is used to decide the new order of elements in the respective data
structure.
In this way, the largest element is moved to the rightmost end at first.
This process is then continued to find the second largest and place it and so on until the data is sorted.
Let us understand the working of bubble sort with the help of the following illustration:
Java + DSA
Bubble sort Code:
int i, j, temp;
boolean swapped;
temp = arr[j];
arr[j + 1] = temp;
Java + DSA
Time Complexity: O(N2), it compares every element with every other element in the worst-case scenario
Average Case O(n2), to compare and swap elements multiple times, especially when the list is unsorted or
partially sorted
Best Case O(n),When the list is already sorted, requiring just one pass to confirm the sorted order. (after
optimization)
Worst Case O(n2),When the list is sorted in reverse order, leading to maximum comparisons and swaps in each
iteration.
//optimized code
int i, j, temp;
boolean swapped;
swapped = false;
temp = arr[j];
arr[j + 1] = temp;
swapped = true;
if (swapped == false)
break;
Now after optimization best case time complexity will become O(n)
Stable and Unstable sort
Stable sort: A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in
sorted output as they appear in the input data set
Unstable Sort: An unstable sort does not guarantee the preservation of the original order of equal elements
Java + DSA
Some Sorting Algorithms are stable by nature, such as Bubble Sort, Insertion Sort, Merge Sort, Count Sort, etc
Unstable Sorting Algorithms: Quick Sort, Heap Sort, Selection Sort
Consider = {6,5,4,3,2,1}
//in first iteration 6 will swap with 5 then 4 upto 1 total 5 swaps
//third=>3swap,2nd=>2swaps,last=>1 swap
int n = arr.length;
int swaps = 0;
boolean swapped;
swapped = false;
Java + DSA
// Swap elements
arr[j + 1] = temp;
swaps++;
swapped = true;
if (!swapped) {
break;
return swaps;
System.out.println();
Q. Sort a String in decreasing order of values associated after removal of values smaller than X.
Input: X = 79, str = “Even 78 Bob 99 Suzy 88 Alice 86”
Explanation: “Even 78” is removed, since the number associated to it is smaller than X(= 79) Now, the reordered
string string based on decreasing order of numbers associated is “Bob 99 Suzy 88 Alice 86”.
Code:
import java.util.ArrayList;
import java.util.List;
Java + DSA
public static List<String> tokenizer(String Str) {
List.add(s);
return List;
int l = List.size();
if (Integer.parseInt(List.get(i)) < x) {
List.remove(i - 1);
List.remove(i - 1);
l = List.size();
List.set(j + 2, temp1);
List.set(j + 1, temp2);
Java + DSA
// Driver Code
int x = 77;
// Function call
System.out.println(Str);
Code Explanation: The idea is to use the Bubble Sort technique. Follow the steps below to solve the problem:
Split the string in to a list, then remove the entries that are less than the given value i.e. X.
Sort the list based on the number associated with it using bubble sort method.
If the numbers are not equal, sort the numbers in decreasing order and simultaneously sort the names.
Swap both the strings and the number together in order to keep them together.
Q. Push zeroes to end while maintaining the relative order of other elements.
Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
Code:
{
if (arr[i] != 0)
arr[count++] = arr[i];
arr[count++] = 0;
Java + DSA
Explanation: Traverse the given array ‘arr’ from left to right. While traversing, maintain count of non-zero
elements in array. Let the count be ‘count’. For every non-zero element arr[i], put the element at ‘arr[count]’ and
increment ‘count’. After complete traversal, all non-zero elements have already been shifted to front end and
‘count’ is set as index of first 0. Now all we need to do is run a loop that makes all elements zero from ‘count’ till
end of the array.
Time Complexity: O(n) ,traversing the array only once
Auxiliary Space: O(1), not using any extra space
Selection Sort: Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the
smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.
Dry Run of selection sort:
int n = arr.length;
int min_idx = i;
min_idx = j;
Java + DSA
// Swap the found minimum element with the first
// element
arr[min_idx] = arr[i];
arr[i] = temp;
Time Complexity: The time complexity of Selection Sort is O(N2) as there are two nested loops
Auxiliary Space: O(1) as the only extra memory used is for temporary variables
Insertion Sort: To sort an array of size N in ascending order iterate over the array and compare the current
element (key) to its predecessor, if the key element is smaller than its predecessor, compare it to the elements
before. Move the greater elements one position up to make space for the swapped element.
The simple steps of achieving the insertion sort are listed as follows -
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to the next element.
Else, shift greater elements in the array towards the right.
Dry Run:
Java + DSA
Code:
int n = arr.length;
int j = i - 1;
arr[j + 1] = arr[j];
j = j - 1;
arr[j + 1] = key;
Time Complexity: O(N^2), in the worst case, each element requires comparison and potential shifting with
every preceding element before finding its correct position in the sorted sequence
[1,2,3,6,4]
[1,3,2,4,6]
[1,3,2,6,4]
[2,3,1,4,6]
Ans. [1,3,2,6,4], as in first run minimum element will be swapped by first element
Q. Which sorting technique is used here?
A player is sorting a deck of cards numbered from 1 to 52. She first picks one card then picks the next card
and puts it after the first card if if it is bigger or before the first card if it is smaller, then she picks another card
and puts it into its proper position.
Java + DSA
a. Bubble sort
b. Insertion sort
c. Selection sort
d. None of these
Ans. Insertion Sort,each card is placed in its correct position by comparing it sequentially with the sorted cards
and shifting elements as needed, resulting in a progressively sorted deck.
a) Insertion sort
b) Selection sort
c) Bubble sort
d) None of these
Ans. Selection Sort, Selection Sort is not stable because it doesn't ensure the preservation of the original order of
equal elements.During the selection and swapping process, elements with the same value might change their
relative positions in the sorted sequence compared to their original order in the input
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority
element always exists in the array.
Output: 2
Code:
class Solution {
Arrays.sort(nums);
int n = nums.length;
return nums[n/2];
Explanation: Sort the array using any algorithm in non-dereasing order, since majority element occurs more
than n/2 times it will always be present at middle position in sorted array so return element at index n/2
Q. Given an array with N distinct elements, convert the given array to a form where all elements are in the
range from 0 to N-1. The order of elements is the same, i.e., 0 is placed in the place of the smallest element, 1 is
placed for the second smallest element, … N-1 is placed for the largest element.
Java + DSA
public static void convert(int arr[], int n)
// of arr[] to temp
Arrays.sort(temp);
// to n-1
int val = 0;
umap.put(temp[i], val++);
// umap
arr[i] = umap.get(arr[i]);
Explanation: The idea is to sort the given array and use an unordered map to store the reduced form of each
value of array then update the whole array to its reduced form using values from unordered map.
Time complexity: O(N * log N),bcz of soring
Assume you are an awesome parent and want to give your children some cookies. But, you should give each
child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with;
and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be
content. Your goal is to maximize the number of your content children and output the maximum number.
Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor
is 1 content.
Java + DSA
Code:
int i = 0;
Arrays.sort(g);
Arrays.sort(s);
return i;
Explanation: sort both the array , now using greedy approach check if the current cookie satisfy the current
children sicne after sorting this will child minimum satisfaction cost
If not move to next cookie, if yes increase the count then return the ans
Q. Given an array, arr[] containing ‘n’ integers, the task is to find an integer (say K) such that after replacing
each and every index of the array by |ai – K| where ( i ∈ [1, n]), results in a sorted array. If no such integer
exists that satisfies the above condition then return -1.
nput: arr[ ] = [10, 5, 4, 3, 2, 1]
Output: 8
Explanation: Upon performing the operation |ai-8|, we get [2, 3, 4, 5, 6, 7] which is sorted.
Code:
int l = 0;
int r = 1000000000;
l = Math.max(l,
Java + DSA
}
if (l > r) {
System.out.println(-1);
else {
System.out.println(l);
Explanation: For the array to be sorted each pair of adjacent elements should be sorted. That means few cases
arise if we take care for particular ai and ai+1 and those are as follows:
If (K <ai) then upon (ai – K < ai+1 – K) the elements will be as it is (ai < ai+1).
If (K > ai) then upon ( K – ai > K – ai+1 ) the elements will be as it is (ai > ai+1).
So, K should be midway between ai and ai+1 that is K should be K = (ai + ai+1)/2 .
Similarly for (ai > ai+1) the value of k would be K = (ai + ai+1)/2
Finally we will take the minimum of all for which (K < ai) and maximum of all for which (K > ai).
Java + DSA
THANK
YOU !