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]

  1. **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.
  2. **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.
  3. **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.
  4. **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.
  5. **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).
  6. **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.
  7. **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:

Practice Problems on Array Sorting

You can improve your understanding of array sorting by solving different problems based on their difficulty level.

**Easy Problems:

**Medium Problems:

**Hard Problems:

**Quick Links :

Similar Reads

Basic operations in Array









Easy problems on Array















Intermediate problems on Array














Hard problems on Array