Merge Sorted Array——Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        nums1[:] = nums1[:m]
        nums2[:] = nums2[:n]
        nums1.extend(nums2)
        nums1.sort()

 

Here is an implementation of mergesort algorithm in C to sort an array: ```c #include <stdio.h> void merge(int arr[], int left, int mid, int right) { int i, j, k; int n1 = mid - left + 1; int n2 = right - mid; int L[n1], R[n2]; for(i = 0; i < n1; i++) L[i] = arr[left + i]; for(j = 0; j < n2; j++) R[j] = arr[mid + 1 + j]; i = 0; j = 0; k = left; while(i < n1 && j < n2) { if(L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while(i < n1) { arr[k] = L[i]; i++; k++; } while(j < n2) { arr[k] = R[j]; j++; k++; } } void mergesort(int arr[], int left, int right) { if(left < right) { int mid = left + (right - left) / 2; mergesort(arr, left, mid); mergesort(arr, mid + 1, right); merge(arr, left, mid, right); } } void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printf("Given array is \n"); printArray(arr, arr_size); mergesort(arr, 0, arr_size - 1); printf("\nSorted array is \n"); printArray(arr, arr_size); return 0; } ``` The `merge` function takes the left, middle, and right indices of the array as input and merges the two subarrays left to mid and mid+1 to right into a single sorted array. The `mergesort` function recursively divides the input array into two halves, sorts them, and then merges them using the `merge` function. The `printArray` function is used to print the elements of an array. In the main function, we define an array of integers, print the array before sorting, call the mergesort function to sort the array, and print the sorted array.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值