(Easy) Sort an Array - LeetCode
Description:
Given an array of integers nums
, sort the array in ascending order.
Example 1:
Input: [5,2,3,1] Output: [1,2,3,5]
Example 2:
Input: [5,1,1,2,0,0] Output: [0,0,1,1,2,5]
Note:
1 <= A.length <= 10000
-50000 <= A[i] <= 50000
Accepted
22,111
Submissions
35,011
Solution:
first attempt:
bubble sort. (Time out Exception)
class Solution { public int[] sortArray(int[] nums) { if(nums ==null||nums.length ==0){ return null; } //bubble sort; for(int i = 0; i<nums.length-1;i++){ for(int j = 0; j< nums.length-i-1; j++){ if(nums[j]>nums[j+1]){ int tmp = nums[j]; nums[j]=nums[j+1]; nums[j+1]=tmp; } } } return nums; } }
Attempt 2 . Quick Sort
class Solution { public int[] sortArray(int[] nums) { if(nums ==null||nums.length ==0){ return null; } sort(nums,0,nums.length-1); return nums; } int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j=low; j<high; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ void sort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi-1); sort(arr, pi+1, high); } } }