diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..691a8f6 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "C_Cpp.errorSquiggles": "Disabled" +} \ No newline at end of file diff --git a/mergesort.cpp b/mergesort.cpp new file mode 100644 index 0000000..7b0267c --- /dev/null +++ b/mergesort.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; + +void Merge(int *a, int low, int high, int mid){ + int i, j, k, temp[high-low+1]; + i = low; + k = 0; + j = mid + 1; + while (i <= mid && j <= high){ + if (a[i] < a[j]){ + temp[k] = a[i]; + k++; + i++; + } + else{ + temp[k] = a[j]; + k++; + j++; + } + } + + while (i <= mid){ + temp[k] = a[i]; + k++; + i++; + } + + while (j <= high){ + temp[k] = a[j]; + k++; + j++; + } + + for (i = low; i <= high; i++){ + a[i] = temp[i-low]; + } +} + +void MergeSort(int *a, int low, int high){ + int mid; + if (low < high){ + mid=(low+high)/2; + MergeSort(a, low, mid); + MergeSort(a, mid+1, high); + + Merge(a, low, high, mid); + } +} + +int main(){ + int n, i; + cout << "Enter size of array: "; + cin >> n; + + int arr[n]; + for(i = 0; i < n; i++){ + cout << "Enter element: "; + cin >> arr[i]; + } + + MergeSort(arr, 0, n-1); + + cout << "\nSorted Array: "; + for (i = 0; i < n; i++) + cout << arr[i] << " "; + + return 0; +} \ No newline at end of file diff --git a/mergesort.py b/mergesort.py new file mode 100644 index 0000000..d5037a1 --- /dev/null +++ b/mergesort.py @@ -0,0 +1,43 @@ +def merge_sort(list, left_index, right_index): + if left_index >= right_index: + return + + middle = (left_index + right_index)//2 + merge_sort(list, left_index, middle) + merge_sort(list, middle + 1, right_index) + merge(list, left_index, right_index, middle) + + +def merge(list, left_index, right_index, middle): + + left_sub = list[left_index:middle + 1] + right_sub = list[middle+1:right_index+1] + + left_sub_index = 0 + right_sub_index = 0 + sorted_index = left_index + + while left_sub_index < len(left_sub) and right_sub_index < len(right_sub): + + if left_sub[left_sub_index] <= right_sub[right_sub_index]: + list[sorted_index] = left_sub[left_sub_index] + left_sub_index = left_sub_index + 1 + else: + list[sorted_index] = right_sub[right_sub_index] + right_sub_index = right_sub_index + 1 + + sorted_index = sorted_index + 1 + + while left_sub_index < len(left_sub): + list[sorted_index] = left_sub[left_sub_index] + left_sub_index = left_sub_index + 1 + sorted_index = sorted_index + 1 + + while right_sub_index < len(right_sub): + list[sorted_index] = right_sub[right_sub_index] + right_sub_index = right_sub_index + 1 + sorted_index = sorted_index + 1 + +list = [32,-23,43,65,190,90] +merge_sort(list, 0, len(list) -1) +print(list) \ No newline at end of file