Sort題型總結

2021-02-20 Arthur的奇妙冒險
Sort題型總結
1.Selection Sort 選擇排序

Given an array of integers, sort the elements in the array in ascending order. The selection sort algorithm should be used to solve this problem.

Clarification: The input is an int[] array which is unsorted, and the output should be sorted int[]array.

Assumption: Null.

Result: Firstly we should check the corner case: if array == null || array.length <= 1, we just return the array and do nothing;

high level idea: we use two pointers, i and j, and with the iteration of i, we maintain the globalmin with the iteration of j, and swap to the first; keep all element before i are sorted.

Test: {4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6}.

public class Solution {
  public int[] selectionSort(int[] array) {
    if (array == null || array.length <= 1) {
      return array;
    }
    for (int i = 0; i < array.length; i++) {
      int min = i;
      for (int j = i + 1; j < array.length; j++) {
        if (array[min] > array[j]) {
          min = j;
        }
      }
      swap(array, i, min);
    }
    return array;
  }

  private void swap(int[] array, int left, int right) {
    int tmp = array[left];
    array[left] = array[right];
    array[right] = tmp;
  }
}

Time ComplexitySpace ComplexityO(n^2)O(1)I, j 兩個for循環go over一遍arrayIn place的操作,不需要額外matintain空間

2.Merge Sort 歸併排序

Given an array of integers, sort the elements in the array in ascending order. The merge sort algorithm should be used to solve this problem.

Clarification: The input is an int[] array which is unsorted, and the output should be sorted int[]array.

Assumption: Null.

Result: Firstly we should check the corner case: if array == null || array.length <= 1, we just return the array and do nothing;

high level idea: in split part, we keep finding the middle of the array, and split into two arrays, then we call the recursion function; in merge part, we merge two arrays, and sort them to one array.

Test: {4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6}.

public class Solution {
  public int[] mergeSort(int[] array) {
    if (array == null || array.length == 0) {
      return array;
    }
    return mergeSort(array, 0, array.length - 1);
  }

  private int[] mergeSort(int[] array, int left, int right) {
    if (left >= right) {
      return new int[] {array[left]};
    }
    int mid = left + (right - left) / 2;
    int[] leftResult = mergeSort(array, left, mid);
    int[] rightResult = mergeSort(array, mid + 1, right);
    return merge(leftResult, rightResult);
  }

  private int[] merge(int[] leftResult, int[] rightResult) {
    int[] result = new int[leftResult.length + rightResult.length];
    int i = 0; int j = 0; int k = 0;
    while (i < leftResult.length && j < rightResult.length) {
      if (leftResult[i] < rightResult[j]) {
        result[k] = leftResult[i];
        i++;
        k++;
      }
      else {
        result[k] = rightResult[j];
        j++;
        k++;
      }
    }
    while (i < leftResult.length) {
      result[k] = leftResult[i];
      i++;
      k++;
    }
    while (j < rightResult.length) {
      result[k] = rightResult[j];
      j++;
      k++;
    }
    return result;
  }
}

Time ComplexitySpace ComplexityO(n) + O(nlogn) = O(nlogn)O(n)Split部分 + Merge部分recursio tree上一條直上直下的路徑和
3.Quick Sort 快速排序

Given an array of integers, sort the elements in the array in ascending order. The quick sort algorithm should be used to solve this problem.

Clarification: The input is an int[] array which is unsorted, and the output should be sorted int[]array.

Assumption: Null.

Result: Firstly we should check the corner case: if array == null || array.length <= 1, we just return the array and do nothing;

high level idea: firstly, we catch a pivot randomly, move it to the right, then we keep two indexes: i and j, and do the comparison and swap, the physical meaning of them are: move all numbers smaller than the pivot to the left of i, and move all numbers larger or equal than the pivot to the right of j; finally we swap back the  i and pivot, and repeat.

Test: {4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6}.

public class Solution {
  public int[] quickSort(int[] array) {
    if (array == null || array.length == 0) {
      return array;
    }
    quickSort(array, 0, array.length - 1);
    return array;
  }

  private void quickSort(int[] array, int left, int right) {
    if (left >= right) {
      return;
    }
    int pivotPos = partition(array, left, right);
    quickSort(array, left, pivotPos - 1);
    quickSort(array, pivotPos + 1, right);
  }

  private int partition(int[] array, int left, int right) {
    int pivotIndex = left + (int)(Math.random() * (right - left + 1));
    int pivot = array[pivotIndex];
    swap(array, pivotIndex, right);
    int i = left;
    int j = right;
    while (i <= j) {
      if (array[i] < pivot) {
        i++;
      }
      else if (array[j] >= pivot) {
        j--;
      }
      else {
        swap(array, i, j);
        i++;
        j--;
      }
    }
    swap(array, i, right);
    return i;
  }

  private void swap(int[] array, int left, int right) {
    int tmp = array[left];
    array[left] = array[right];
    array[right] = tmp;
  }
}

Time ComplexitySpace ComplexityAverage O(nlogn), Worst case O(n^2)Average O(n)兩個for循環go over一遍arrayrecursio tree上一條直上直下的路徑和
4.Rainbow Sort 彩虹排序

Given an array of balls, where the color of the balls can only be Red, Green or Blue, sort the balls such that all the Red balls are grouped on the left side, all the Green balls are grouped in the middle and all the Blue balls are grouped on the right side. (Red is denoted by -1, Green is denoted by 0, and Blue is denoted by 1).

Clarification: The input is an int[] array which is unsorted, and the output should be sorted int[]array.

Assumption: The input array is not null.

Result: Firstly we should check the corner case: if array == null || array.length <= 1, we just return the array and do nothing;

high level idea: we keep three indexes: i, j and k, split the array into four regions:

i = 0 -> : all letters to the left-hand side of i (not including i) are all "a"s

j = 0 -> : all letters in [i, j) (including i, but not including j) are all "b"s j is the current index

[j, k] : unexplored area (including j and k)

k = <- n - 1: all letters to the right-hand side of k (not including k) are all "c"s.

Test: {1, 0, 1, -1, 0} is sorted to {-1, 0, 0, 1, 1}.

public class Solution {
  public int[] rainbowSort(int[] array) {
    if (array == null || array.length <= 1) {
      return array;
    }
    int i = 0;
    int j = 0;
    int k = array.length - 1;
    while (j <= k) {
      if (array[j] == -1) {
        swap(array, i, j);
        i++;
        j++;
      }
      else if (array[j] == 0) {
        j++;
      }
      else {
        swap(array, j, k);
        k--;
      }
    }
    return array;
  }

  private void swap(int[] array, int left, int right) {
    int tmp = array[left];
    array[left] = array[right];
    array[right] = tmp;
  }
}

Time ComplexitySpace ComplexityO(n)O(1)兩個for循環go over一遍arrayIn place的操作,不需要額外matintain空間

相關焦點

  • Graph 新題型 Min Swaps to Sort Array
    後來經人提示才發現實際上這是一道披著 sort 外衣的 graph 題目。」最近我的小夥伴問了一道題非常有趣。題目不難,但是我之前從來沒有遇到過,所以好好研究了一下。現在分享給大家,有更好的解法的同學可以指點我,如果沒見過這題的我們可以一起探討。
  • Python中的Timsort算法,Timsort算法的優缺點,中級python技術點
    Python中的Timsort算法Timsort算法被認為是一種混合排序算法,因為它採用了插入排序和合併排序的兩種方法的最佳組合。Timsort對於Python社區來說非常重要,因為它是由Tim Peters在2002年創建的,用於作為Python語言的標準排序算法。Timsort的主要特點是它利用了存在於大多數真實數據集中的已經排序的元素。
  • CentOS Linux系統的排序命令sort
    CentOS Linux學習筆記總結(八十五)-CentOS Linux系統的排序命令sortsort命令是linux系統中非常常用的一個排序命令,sort的工作原理就是將文件的每一行作為一個單位,相互比較,比較原則是從首字符向後,依次按ASCII碼進行比較,然後按照順序輸出。
  • Python 中的 L.sort() 與 sorted()
    但是,Python中也有內置的排序函數,比如 L.sort() 和 sorted() 函數。但是它們有什麼區別呢?L.sort():該函數的三個參數和 sorted() 的後三個參數含義是一致的,而需要特別注意的是,該函數隻適用於列表,而非任意可以迭代的對象。cmp是比較函數,接受兩個對象參數 x 和 y,返回 負數(x<y),0(x=y),正數(x>y)。
  • 指數函數經典題型總結
    指數函數經典題型總結(更多資料和更詳細的例題解答和解題技巧,請關注+評論!如果對大家有幫助,歡迎轉發幫助更多學子!!!)指數函數是高中數學的基本函數之一,也是高考的常考題型,因此必須掌握。今天小編和大家分享一下指數函數的基礎知識和常見題型,以供參考。
  • Python學習第182課——sort排序
    sort就是這樣的一個排序命令。●sortsort的作用就是對文本文件的行進行排序。每學習一個新的命令,我們都可以用man查看它的說明。關於sort的說明,大家可以自行查看。在這裡,我們給名字做一個最簡單的排序,所以可以不用它的option,我們直接sort後面跟文件名就行。
  • 多目標跟蹤:SORT和Deep SORT
    論文地址:https://arxiv.org/abs/1602.00763論文代碼:https://github.com/abewley/sort算法總覽多目標跟蹤被視為數據關聯問題,在視頻幀序列中進行跨檢測結果的關聯,為了解決數據相關的問題,跟蹤器使用了多種方法對運動過程和運動目標的外觀特徵進行建模!
  • 面試官系列 - LeetCode鍊表知識點&題型總結
    前段時間,我恰好總結了 LeetCode 常見的面試算法題目。今天分享給大家。剛開始準備刷算法題目的時候,感覺真的是好難,十道題目有九道是不會的。心中曾一萬隻草泥馬跑過,自己怎麼這麼辣雞。慢慢得,我發現算法也是一個可以通過練習慢慢成長的。首先我們要掌握基本的數據結構,數組,鍊表,哈希表, Set,二叉樹,堆,棧等。
  • 中考求陰影部分面積題型總結
    求平面圖形陰影部分面積是中考中常見的題型,也是失分比較高的地方。平面陰影部分面積常常以填空題,選擇題的形式出現,有時也會出現在解答題中。下面總結幾種類型供大家參考!題型一 直接套用公式求陰影面積此類題型相對簡單,陰影部分形狀單一,可以直接根據圖形形狀,套用對應公式,直接求解得出陰影部分面積。
  • C++ sort 排序函數用法
    函數,因為自己寫的快排寫不好真的沒有sort快,所以毅然決然選擇sort函數用法1、sort函數可以三個參數也可以兩個參數,必須的頭文件#include < algorithm>和using namespace std;2、它使用的排序方法是類似於快排的方法,時間複雜度為n*log2(n)3、Sort函數有三個參數:(第三個參數可不寫)(
  • 2018高考數學二項式定理的題型總結
    同學們好,二項式定理是理科生的專利,當然理科生需要總結歸納二項式定理有哪些題型和變形。今天小新老師就將這些知識總結歸納出來,以供參考借鑑。題型一、通項係數問題 這類問題一般是求解常數項是多少?或者某一項的係數是多少?
  • 分式必會題型總結,你會幾個?
    分式必會題型總結,你會幾個?初中我們研究的有理式包括整式和分式,我們知道整式研究的是單項式和多項式,那分式研究什麼呢?這節課我們一起來研究一下分式必會題型,你看能做對幾個?分式題型一:不改變分式的值,把下列各式的分子與分母的各項係數都化為整數。分式題型一思路分析:該類題型考查的是分式的基本性質:分子分母同乘以一個不為0的整式分數的值不變。第(1)題首先分子分母同乘以100,可得分子為x-500,分母變為30x+4,並且分子分母除了1沒有其他公因式了,這時候我們把分子分母化為整式了。
  • 高中英語閱讀理解專項題型總結
    高中英語閱讀理解專項題型總結為了幫助學生對高中英語閱讀理解這一部分能有所提升,下面是小編整理的高中英語閱讀理解專項題型總結,希望對大家有所幫助。高中英語閱讀理解專項題型總結Most people usually traveled by ship and train which are driven by steam engine. It played an important part in many kinds of vehicles several scores of years ago.
  • 高中數學之三角函數題型總結(上)
    昨天為大家總結了關於數列的題型。今天為大家總結和歸納一下數學三角函數有關的題型。高中數學三角函數,我們在做題的時候,遇到問題複雜一點的就不知道如何下手去做或者沒思路,弄不明白要怎麼解決。今天就圍繞三角函數展開來總結和歸納三角函數的基礎知識和題型。只有把基礎打好,才能在做題時得心用手,不會無從下手。三角函數在高考中考查比較多,屬於必須要得的分數。需要我們對三角函數的知識點牢牢掌握。
  • JavaScript函數補完:sort()排序
    JavaScript實現多維數組、對象數組排序,其實用的就是原生的sort()方法,用於對數組的元素進行排序。
  • 高考題型之數列問題總結歸納
    大家好,我是試題小講,今天為大家總結一下關於高考數學題型之一的數列問題,考查數列通常都是在大題中出現。總結一下主要考查題型。高中階段就學過等差數列和等比數列。先來總結一下他們的通項公式和求和公式及性質。
  • 美劇每日一句:sort of
    Last week, when Mike and I went to the park searching for Zach, I sort of found him.No!Yes, and I gave him money and I sent him away and I didn’t tell Mike.Holy crap!
  • Excel – 多條件排序就用 sortby 函數
    O365 這次出了兩個排序函數,除了前段時間給大家講解過的 sort 以外,還有一個 sortby 函數。sortby 函數也是用於排序,功能跟 sort 類似,主要區別在於:有關 sort 函數的詳解,請參閱 Excel – 告別繁瑣的菜單操作
  • 適合高一英語的閱讀理解題型總結
    適合高一英語的閱讀理解題型總結高一是高中英語打基礎的一年,要想為高中英語打下堅固的基礎,就要時常做練習做積累。下面是小編為大家整理的適合高一英語的閱讀理解題型總結,希望對大家有所幫助。適合高一英語的閱讀理解題型一Mr.
  • 反比例函數的應用題型總結,全面又經典,點開來看一下
    反比例函數的應用題型總結,全面又經典,點開來看一下反比例函數的應用是反比例函數圖像和性質的綜合運用,要想這章考個高分,反比例函數的應用一定要學好,一定要注重學生的分析思考能力,接下來老師總結了反比例函數的應用題型,全面又經典。