Array Sorting Practice Problems (original) (raw)
Last Updated : 24 Sep, 2024
**Sorting an array means arranging the elements of the array in a certain order. Generally sorting in an array is done to arrange the elements in increasing or decreasing order.
**Problem statement: Given an array of integers arr
, the task is to sort the array in ascending order and return it, **without using any built-in functions.
**Example:
**Input: arr = [5, 2, 4, 3, 1]
**Output: [1, 2, 3, 4, 5]**Input: arr = [1, 2, 2, 1, 3, 5, 4]
**Output: [1, 1, 2, 2, 3, 4, 5]
Popular Sorting Algorithms:
- **Bubble Sort****:** Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large arrays as its average and worst-case time complexity is quite high.
- **Selection Sort****:** Selection sort is another sorting technique in which we find the minimum element in every iteration and place it in the array beginning from the first index. Thus, a selection sort also gets divided into a sorted and unsorted subarray.
- **Insertion Sort****:** Insertion sort similarly to the way we sort playing cards in our hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed in the correct position in the sorted part.
- **Merge Sort****:** It is a sorting algorithm that is based on the Divide and Conquer paradigm. In this algorithm, the array is repeatedly divided into two equal halves and then they are combined in a sorted manner.
- **Quick Sort****:** This is a sorting algorithm based on the divide and conquer approach where an array is divided into subarrays by selecting a pivot element (element selected from the array).
- **Heap Sort****:** Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to the selection sort where we first find the minimum element and place the minimum element at the beginning. Repeat the same process for the remaining elements.
- **Counting Sort****:** Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of elements having distinct key values (kind of hashing). Then do some arithmetic to calculate the position of each element in the output sequence.
To learn more about all other types of Sorting Algorithms, refer to the below articles:
Comparison of Sorting Algorithms:
**Complexity of Sorting Algorithms | **Best Case | **Average Case | **Worst Case | **Memory | **Stable | **Method Used |
---|---|---|---|---|---|---|
Quick Sort | N * logN | N * logN | N2 | N | No | Partitioning |
Merge Sort | N * logN | N * logN | N * logN | N | Yes | Merging |
Heap Sort | N * logN | N * logN | N * logN | 1 | No | Selection |
Insertion Sort | N | N2 | N2 | 1 | Yes | Insertion |
Selection Sort | N2 | N2 | N2 | 1 | No | Selection |
Bubble Sort | N | N2 | N2 | 1 | Yes | Exchanging |
Counting Sort | N+K | N+K | N+K | N+K | Yes | Hashing |
Implementing of Sorting Algorithm:
Below is a simple implementation of Bubble Sort Algorithms to sort the Array:
C++ `
#include <bits/stdc++.h> using namespace std;
// Function to sort the array using Bubble Sort void sortArray(vector& arr){ int n = arr.size();
for (int i = 0; i < n - 1; i++) {
bool swapped = false;
// Last i elements are already in place
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true;
}
}
// If no two elements were swapped by inner loop,
// then break
if (!swapped)
break;
}
}
void print(const vector& arr){ for(int num : arr) cout << num << " "; cout << endl; }
int main(){ vector arr = {64, 34, 25, 12, 22, 11, 90}; sortArray(arr); cout << "Sorted array: \n"; print(arr); return 0; }
C
#include <stdio.h>
// Function to sort the array using Bubble Sort void sortArray(int arr[], int n) {
// Outer loop to traverse the array
for (int i = 0; i < n - 1; i++) {
int swapped = 0;
// Last i elements are already in place
for (int j = 0; j < n - i - 1; j++) {
// If the current element is greater than the next element
if (arr[j] > arr[j + 1]) {
// Swap the elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1;
}
}
// If no two elements were swapped by inner loop,
// then break the loop
if (!swapped)
break;
}
}
void printArray(int arr[], int size) { for (int i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); }
int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int N = sizeof(arr) / sizeof(arr[0]); sortArray(arr, N); printf("Sorted array: \n"); printArray(arr, N); return 0; }
Java
import java.util.Arrays;
class GfG {
// Function to sort the array using Bubble Sort
static void sortArray(int[] arr) {
int n = arr.length;
// Outer loop to traverse the array
for (int i = 0; i < n - 1; i++) {
boolean swapped = false;
// Last i elements are already in place
for (int j = 0; j < n - i - 1; j++) {
// If the current element is greater
// than the next element
if (arr[j] > arr[j + 1]) {
// Swap the elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true; // Set swapped to true
}
}
// If no two elements were swapped by inner loop,
// then break the loop
if (!swapped)
break;
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
sortArray(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
}
Python
Function to sort the array using Bubble Sort
def sortArray(arr): n = len(arr)
# Outer loop to traverse the array
for i in range(n - 1):
swapped = False
# Last i elements are already in place
for j in range(n - i - 1):
# If the current element is greater
# than the next element
if arr[j] > arr[j + 1]:
# Swap the elements
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
# If no two elements were swapped by inner loop,
# then break the loop
if not swapped:
break
Driver code
arr = [64, 34, 25, 12, 22, 11, 90] sortArray(arr) print("Sorted array:", arr)
C#
using System;
class GfG {
// Function to sort the array using Bubble Sort
static void SortArray(int[] arr) {
int n = arr.Length;
// Outer loop to traverse the array
for (int i = 0; i < n - 1; i++) {
bool swapped = false;
// Last i elements are already in place
for (int j = 0; j < n - i - 1; j++) {
// If the current element is greater
// than the next element
if (arr[j] > arr[j + 1]) {
// Swap the elements
int 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 the loop
if (!swapped)
break;
}
}
static void Main(string[] args) {
int[] arr = { 64, 34, 25, 12, 22, 11, 90 };
SortArray(arr);
Console.WriteLine("Sorted array: " + string.Join(" ", arr));
}
}
JavaScript
// Function to sort the array using Bubble Sort function sortArray(arr) { let n = arr.length;
// Outer loop to traverse the array
for (let i = 0; i < n - 1; i++) {
let swapped = false;
// Last i elements are already in place
for (let j = 0; j < n - i - 1; j++) {
// If the current element is greater
// than the next element
if (arr[j] > arr[j + 1]) {
// Swap the elements
let 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 the loop
if (!swapped)
break;
}
}
// Driver code let arr = [64, 34, 25, 12, 22, 11, 90]; sortArray(arr); console.log("Sorted array:", arr.join(" "));
`
Output
Sorted array: 11 12 22 25 34 64 90
**Complexity Analysis to Sort an Array using Bubble Sort:
**Time Complexity: O(N2)
**Auxiliary Space: O(1)
Important Terminologies in Array Sorting:
Here we will see several algorithms used for array sorting. But before that let us see some important terminologies related to sorting:
- **In-Place Sorting****:** In-place sorting means arranging the elements without using any extra space other than the given array.
- **Stability of Sorting****:** A sorting algorithm is said to be stable if the relative order of the same valued elements is preserved in the final sorted array i.e., the relative order of the same valued elements in the sorted array is the same as in the original array.
Practice Problems on Array Sorting
You can improve your understanding of array sorting by solving different problems based on their difficulty level.
**Easy Problems:
- Program to check if an array is sorted or not (Iterative and Recursive)
- Print sorted distinct elements of array in C++
- Print All Distinct Elements of a given integer array
- Alternative Sorting
- Sort an array in wave form
- Sort on the basis of number of factors using STL
- Sort an array which contain 1 to n values
- Sort 1 to N by swapping adjacent elements
- Sort elements by frequency | Set 1
- Sort an array containing two types of elements
- Sort an array according to absolute difference with given value
- Sorting all array elements except one
- Minimum product pair an array of positive Integers
- Minimum adjacent swaps required to Sort Binary array
- Pairs with Difference less than K
**Medium Problems:
- Sort a nearly sorted (or K sorted) array
- Count Inversions in an array | Set 1 (Using Merge Sort)
- Union and Intersection of two sorted arrays
- Sort an array of 0s, 1s and 2s
- Check if reversing a sub array make the array sorted
- Merge 3 Sorted Arrays
- Sorting array except elements in a subarray
- Count all distinct pairs with difference equal to k
- Construct an array from its pair-sum array
- Ropes left after every removal of smallest
- Check if any interval completely overlaps the other
- Maximizing Unique Pairs from two arrays
**Hard Problems:
- Minimum number of swaps required to sort an array
- Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
- Median in a stream of integers (running integers)
- Merge two sorted arrays with O(1) extra space
- Minimum De-arrangements present in array of AP (Arithmetic Progression)
- Divide an array into k segments to maximize maximum of segment minimums
- Maximum number of partitions that can be sorted individually to make sorted
- Rank of all elements in an array
- Merging two unsorted arrays in sorted order
- Sort an array after applying the given equation
- Minimum swaps to make two arrays consisting unique elements identical
**Quick Links :
Similar Reads
- Array Data Structure Complete Guide to ArraysLearn more about Array in DSA Self Paced CoursePractice Problems on ArraysTop Quizzes on Arrays What is Array?An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calcul 3 min read
- What is Array? Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of same data type stored at contiguous memory locations. For simplicity, we can think of an array as a flight of stairs where on each step is placed a value (let's say one of your friends). 2 min read
- Getting Started with Array Data Structure Array is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr 14 min read
- Applications, Advantages and Disadvantages of Array Array is a linear data structure that is a collection of data elements of same types. Arrays are stored in contiguous memory locations. It is a static data structure with a fixed size.Table of ContentApplications of Array Data Structure:Advantages of Array Data Structure:Disadvantages of Array Data 2 min read
- Subarrays, Subsequences, and Subsets in Array What is a Subarray?A subarray is a contiguous part of array, i.e., Subarray is an array that is inside another array. In general, for an array of size n, there are n*(n+1)/2 non-empty subarrays. For example, Consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are: (1), 10 min read