04 Sorting in Array

Updated 4 Oct 2026

  • Sorting is any process of ordering or categorizing items systematically
  • It helps us find items easier and faster when the data are sorted

Insertion Sort

  • วิธีทำสามารถดูได้ที่ Insertion Sort

Performance

  • When data are already in order: O(n)O(n)
  • When data are reverse in order: O(n2)O(n^2)
  • Complexity depends mainly on the number of comparisons and swapping

Selection Sort

  • วิธีทำสามารถดูได้ที่ Selection Sort

Performance

  • When data are already in order: O(n2)O(n^2)
  • When data are reverse in order: O(n2)O(n^2)
  • Complexity depends mainly on the number of comparisons and swapping

Merge Sort

  • วิธีทำสามารถดูได้ที่ Merge Sort

Performance

  • Merge sort using the array data structure requires and extra storage (temp array) of size n2\frac{n}{2} for the divided data and merged data at each round
  • The complexity depends on comparisons, assign data to the temp array, and copying data back to the original array
  • Merge sort has worst case performance of O(nlog⁡n)O(n\log n)

Quick Sort

  • วิธีทำสามารถดูได้ที่ Quick Sort

Limitation

  • It may require an extra storage to save the groups of data +-
  • Selecting a good pivot is also a challenge

Performance

  • The pivot divides the array each time into one big subarray while the other array empty: O(n2)O(n^2)
  • In the best case, the pivot divides the array each time into two parts of about the same size: O(nlog⁡n)O(n\log n)

Sorting Complexity (Big-O)

SortingWhen Data is already in order (Big-O)When data reverse in order (Big-O)
Insertion SortO(n)O(n)O(n2)O(n^2)
Selection SortO(n2)O(n^2)O(n2)O(n^2)
Merge SortO(nlog⁡n)O(n\log n)
Quick SortO(nlog⁡n)O(n\log n)