Understanding Sorting Algorithms With Example

Understanding Sorting Algorithms With Example

ยท

4 min read

Sorting algorithms play a crucial role in computer science and are fundamental to the efficient organization and retrieval of data. In this blog, we will explore various sorting algorithms, focusing on their principles, advantages, and disadvantages. Specifically, we will delve into the realm of Data Structures and Algorithms (DSA) to understand how these sorting methods operate.

Why Sorting Matters?

Sorting is a process of arranging elements in a specific order, making it easier to search and retrieve data. Whether you're dealing with a list of names, numbers, or any other type of information, a well-designed sorting algorithm can significantly enhance the performance of various applications, from databases to search engines.

Common Sorting Algorithms

1. Bubble Sort:

  • Principle: Repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.

  • Example:

      function bubbleSort($arr) {
          $n = count($arr);
    
          for ($i = 0; $i < $n - 1; $i++) {
              for ($j = 0; $j < $n - $i - 1; $j++) {
                  if ($arr[$j] > $arr[$j + 1]) {
                      // Swap elements if they are in the wrong order
                      $temp = $arr[$j];
                      $arr[$j] = $arr[$j + 1];
                      $arr[$j + 1] = $temp;
                  }
              }
          }
    
          return $arr;
      }
    
      $originalArray = [5, 2, 9, 1, 5];
      $sortedArray = bubbleSort($originalArray);
      print_r($sortedArray);
    
      Original List: 5, 2, 9, 1, 5
      Iteration 1: 2, 5, 1, 5, 9
      Iteration 2: 2, 1, 5, 5, 9
      Iteration 3: 1, 2, 5, 5, 9
    
  • Advantages: Simple to implement.

  • Disadvantages: Inefficient for large datasets.

2. Selection Sort:

  • Principle: Divide the list into a sorted and an unsorted region. In each iteration, the smallest element from the unsorted region is selected and swapped with the first element of the unsorted region.

  • Example:

      function selectionSort($arr) {
          $n = count($arr);
    
          for ($i = 0; $i < $n - 1; $i++) {
              $minIndex = $i;
              for ($j = $i + 1; $j < $n; $j++) {
                  if ($arr[$j] < $arr[$minIndex]) {
                      $minIndex = $j;
                  }
              }
    
              // Swap the found minimum element with the first element
              $temp = $arr[$i];
              $arr[$i] = $arr[$minIndex];
              $arr[$minIndex] = $temp;
          }
    
          return $arr;
      }
    
      // Example usage:
      $originalArray = [5, 2, 9, 1, 5];
      $sortedArray = selectionSort($originalArray);
      print_r($sortedArray);
    
      Original List: 5, 2, 9, 1, 5
      Iteration 1: 1, 2, 9, 5, 5
      Iteration 2: 1, 2, 9, 5, 5
      Iteration 3: 1, 2, 5, 9, 5
      Iteration 4: 1, 2, 5, 5, 9
    
  • Advantages: Simple, in-place algorithm.

  • Disadvantages: Inefficient for large datasets.

3. Merge Sort:

  • Principle: Divide the unsorted list into n sub-lists, each containing one element. Repeatedly merges sub-lists to produce new sorted sub-lists until there is only one sub-list remaining.

  • Example:

      function mergeSort($arr) {
          $n = count($arr);
    
          if ($n <= 1) {
              return $arr;
          }
    
          $mid = (int)($n / 2);
          $left = mergeSort(array_slice($arr, 0, $mid));
          $right = mergeSort(array_slice($arr, $mid));
    
          return merge($left, $right);
      }
    
      function merge($left, $right) {
          $result = [];
          $i = $j = 0;
    
          while ($i < count($left) && $j < count($right)) {
              if ($left[$i] < $right[$j]) {
                  $result[] = $left[$i++];
              } else {
                  $result[] = $right[$j++];
              }
          }
    
          return array_merge($result, array_slice($left, $i), array_slice($right, $j));
      }
    
      // Example usage:
      $originalArray = [5, 2, 9, 1, 5];
      $sortedArray = mergeSort($originalArray);
      print_r($sortedArray);
    
      Original List: 5, 2, 9, 1, 5
      Merge 1: 2, 5 | 1, 5, 9
      Merge 2: 1, 2, 5, 5, 9
    
    • Advantages: Efficient for large datasets, stable.

    • Disadvantages: Requires additional space for merging.

4. Quick Sort:

  • Principle: Selects a 'pivot' element and partitions the other elements into two sub-arrays according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively.

  • Example:

function quickSort($arr) {
    $n = count($arr);

    if ($n <= 1) {
        return $arr;
    }

    $pivot = $arr[0];
    $left = $right = [];

    for ($i = 1; $i < $n; $i++) {
        if ($arr[$i] < $pivot) {
            $left[] = $arr[$i];
        } else {
            $right[] = $arr[$i];
        }
    }

    return array_merge(quickSort($left), [$pivot], quickSort($right));
}

// Example usage:
$originalArray = [5, 2, 9, 1, 5];
$sortedArray = quickSort($originalArray);
print_r($sortedArray);
Original List: 5, 2, 9, 1, 5
Pivot: 5
Partition: 2, 1 | 5, 9, 5
Recursive Sort: 1, 2 | 5 | 5, 9
  • Advantages: Efficient for large datasets, in-place sorting.

  • Disadvantages: Not stable, In the worst-case scenario, can have a time complexity of O(n^2), but this is rare and can be mitigated by choosing a good pivot strategy.


Conclusion

Sorting algorithms are fundamental tools in computer science, enabling efficient data manipulation and retrieval. The choice of sorting algorithm depends on factors such as the size of the dataset, stability requirements, and available memory. As you dive deeper into the world of DSA, experimenting with and understanding these sorting algorithms will empower you to make informed decisions in your programming endeavors.

ย