Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2480 from Anukriti167/patch-5
Browse files Browse the repository at this point in the history
Create 0912-sort-an-array
  • Loading branch information
a93a authored May 17, 2023
2 parents 4cc25ec + 1dfb25e commit 535ade4
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions java/0912-sort-an-array
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class Solution {
//Using Merge Sort
public int[] sortArray(int[] nums) {
mergeSort(nums, 0, nums.length-1);
return nums;
}
public void mergeSort(int []arr, int low, int high){
if(low >= high) return;

int mid = (low+high)/2;
mergeSort(arr, low, mid);
mergeSort(arr, mid+1, high);
merge(arr, low, high, mid);
}
public void merge(int []arr, int low, int high, int mid){
ArrayList<Integer> temp = new ArrayList<>();
int left = low;
int right = mid+1;

while(left <= mid && right <= high){
if(arr[left] <= arr[right]){
temp.add(arr[left]);
left++;
}else{
temp.add(arr[right]);
right++;
}
}
while(left <= mid){
temp.add(arr[left]);
left++;
}
while(right <= high){
temp.add(arr[right]);
right++;
}
for(int i=low; i<= high; i++){
arr[i] = temp.get(i-low);
}
}
}

0 comments on commit 535ade4

Please sign in to comment.