Introduction
In this article, you will learn how to sort an array in ascending order using six common sorting algorithms: Insertion Sort, Bubble Sort, Selection Sort, Merge Sort, Quick Sort, and Heap Sort. These sorting techniques are crucial for understanding algorithmic concepts and optimizing performance in data processing.
1. Insertion Sort
void insertionSort(int arr[], int n) { for (int i = 1; i < n; i++) { int key = arr[i], j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } }
2. Bubble Sort
void bubbleSort(int arr[], int n) { for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } }
3. Selection Sort
void selectionSort(int arr[], int n) { for (int i = 0; i < n-1; i++) { int minIdx = i; for (int j = i+1; j < n; j++) if (arr[j] < arr[minIdx]) minIdx = j; int temp = arr[minIdx]; arr[minIdx] = arr[i]; arr[i] = temp; } }
4. Merge Sort
void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1, n2 = r - m; int L[n1], R[n2]; for (int i = 0; i < n1; i++) L[i] = arr[l + i]; for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; int i = 0, j = 0, k = l; while (i < n1 && j < n2) arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++]; while (i < n1) arr[k++] = L[i++]; while (j < n2) arr[k++] = R[j++]; } void mergeSort(int arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } }
5. Quick Sort
int partition(int arr[], int low, int high) { int pivot = arr[high], i = (low - 1); for (int j = low; j < high; j++) if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return (i + 1); } void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } }
6. Heap Sort
void heapify(int arr[], int n, int i) { int largest = i, l = 2*i+1, r = 2*i+2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; heapify(arr, n, largest); } } void heapSort(int arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i = n - 1; i >= 0; i--) { int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapify(arr, i, 0); } }
Final Output Example
int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); insertionSort(arr, n); // Replace with any sort method
Use the relevant sort function to sort an array in ascending order based on your requirement.
Conclusion
Each sorting algorithm offers a different approach to sorting an array in ascending order. Depending on your data size and performance needs, you can choose the best one. Mastering these sorts helps you in technical interviews and coding assessments.