运行 ❯
获取你
自己的
网站
×
更改方向
更改主题,深色/浅色
前往 Spaces
Python
C
Java
def mergeSort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 leftHalf = arr[:mid] rightHalf = arr[mid:] sortedLeft = mergeSort(leftHalf) sortedRight = mergeSort(rightHalf) return merge(sortedLeft, sortedRight) def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:]) result.extend(right[j:]) return result unsortedArr = [3, 7, 6, -10, 15, 23.5, 55, -13] sortedArr = mergeSort(unsortedArr) print("Sorted array:", sortedArr) #Python
#include <stdio.h> void mergeSort(double arr[], int start, int end); void merge(double arr[], int start, int mid, int end); int main() { double unsortedArr[] = {3, 7, 6, -10, 15, 23.5, 55, -13}; int size = sizeof(unsortedArr) / sizeof(unsortedArr[0]); mergeSort(unsortedArr, 0, size - 1); printf("Sorted array: "); for (int i = 0; i < size; i++) { printf("%.1f ", unsortedArr[i]); } printf("\n"); return 0; } void mergeSort(double arr[], int start, int end) { if (start < end) { int mid = (start + end) / 2; mergeSort(arr, start, mid); mergeSort(arr, mid + 1, end); merge(arr, start, mid, end); } } void merge(double arr[], int start, int mid, int end) { int i, j, k; int n1 = mid - start + 1; int n2 = end - mid; double left[n1], right[n2]; for (i = 0; i < n1; i++) left[i] = arr[start + i]; for (j = 0; j < n2; j++) right[j] = arr[mid + 1 + j]; i = 0; j = 0; k = start; while (i < n1 && j < n2) { if (left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } while (i < n1) { arr[k] = left[i]; i++; k++; } while (j < n2) { arr[k] = right[j]; j++; k++; } } //C
import java.util.Arrays; public class Main { public static void main(String[] args) { double[] unsortedArr = {3, 7, 6, -10, 15, 23.5, 55, -13}; double[] sortedArr = mergeSort(unsortedArr); System.out.println("Sorted array: " + Arrays.toString(sortedArr)); } public static double[] mergeSort(double[] arr) { if (arr.length <= 1) { return arr; } int mid = arr.length / 2; double[] leftHalf = Arrays.copyOfRange(arr, 0, mid); double[] rightHalf = Arrays.copyOfRange(arr, mid, arr.length); double[] sortedLeft = mergeSort(leftHalf); double[] sortedRight = mergeSort(rightHalf); return merge(sortedLeft, sortedRight); } public static double[] merge(double[] left, double[] right) { double[] result = new double[left.length + right.length]; int i = 0, j = 0, k = 0; while (i < left.length && j < right.length) { if (left[i] < right[j]) { result[k++] = left[i++]; } else { result[k++] = right[j++]; } } while (i < left.length) { result[k++] = left[i++]; } while (j < right.length) { result[k++] = right[j++]; } return result; } } //Java
Python 结果
C 结果
Java 结果
排序后的数组: [-13, -10, 3, 6, 7, 15, 23.5, 55]
排序后的数组: -13.0 -10.0 3.0 6.0 7.0 15.0 23.5 55.0
排序后的数组: [-13.0, -10.0, 3.0, 6.0, 7.0, 15.0, 23.5, 55.0]