Middle — Senior
სორტირების ალგორითმების სირთულე რა არის?
sobes.tech AI
პასუხი AI-სგან
සැSorting algorithms' complexity is generally evaluated based on time and memory.
- Bubble Sort: time — O(n²), memory — O(1). Simple, but inefficient for large data.
- Insertion Sort: time — O(n²) in the worst case, O(n) in the best (almost sorted array), memory — O(1).
- Merge Sort: time — O(n log n) in all cases, memory — O(n) due to an additional array.
- Quick Sort: average time — O(n log n), worst — O(n²), memory — O(log n) due to recursion.
- Heap Sort: time — O(n log n), memory — O(1).
Java example of quick sort:
public static 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);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int 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;
}