Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"C_Cpp.errorSquiggles": "Disabled"
}
68 changes: 68 additions & 0 deletions mergesort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include <iostream>
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;
}
43 changes: 43 additions & 0 deletions mergesort.py
Original file line number Diff line number Diff line change
@@ -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)