(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. 1 <= A.length <= 10000
  2. -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); 
        } 
    } 
       
}
 

 

 

转载于:https://www.cnblogs.com/codingyangmao/p/11445984.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值