快速排序和快速選擇(quickSort and quickSelect)算法

排序算法:快速排序(quicksort)遞歸與非遞歸算法
TopK問題:快速選擇(quickSelect)算法

import java.util.*;
import java.lang.*;public class Demo {// 非遞歸 using stackpublic static void quickSortStack(int[] nums, int left, int right) {if (left >= right) return;Stack<Range> stack = new Stack<Range>();stack.push( new Range(left, right) );while( !stack.empty() ) {Range curRange = stack.pop();if (curRange.left < curRange.right) {int pivotIdx = partition(nums, curRange.left, curRange.right);stack.push( new Range(curRange.left, pivotIdx - 1) );stack.push( new Range(pivotIdx + 1, curRange.right) );}}}// recursion quickSortpublic static void quickSort(int[] nums, int left, int right) {if (left < right) {int pIdx = partition(nums, left, right);quickSort(nums, left, pIdx - 1);quickSort(nums, pIdx + 1, right);} }public static int partition(int[] nums, int left, int right) {// nums[left]~nums[retIdx - 1] <= nums[retIdx] <= nums[retIdx ~ right]if (left == right) return left;int pivot = nums[left]; // mark the leftmost value as the pivot. and store it.int lp = left, rp = right;while(lp < rp) {while(lp < rp && nums[rp] >= pivot)rp--;nums[lp] = nums[rp]; //move the smaller value to left Range.while(lp < rp && nums[lp] <= pivot)lp++;nums[rp] = nums[lp]; // move the bigger value to right Range.}nums[lp] = pivot;return lp;}public static void swap(int[] nums, int i, int j) {int tmp = nums[i];nums[i] = nums[j];nums[j] = tmp;}public static int partitionV2(int[] nums, int left, int right) {int l = left;int r = right + 1;int pivot = nums[left];while(true) {while( l < right && nums[++l] < pivot )if ( l == right ) break;while( r > left && nums[--r] >= pivot )if ( r == left ) break;if (l >= r)break;swap(nums, l, r);}swap(nums, left, r);return r;}//TopK問題public static int findKthLargest(int[] nums, int k) {return quickSelect(nums, k, 0, nums.length - 1);}//快速選擇算法public static int quickSelect(int[] nums, int k, int left, int right) {if (left == right) return nums[left];int index = partition(nums, left, right);if ( index - left + 1 == k) {return nums[index];}else if ( index - left + 1 > k ) {return quickSelect(nums, k, left, index - 1);}else {return quickSelect(nums, k - index + left - 1, index + 1, right);}}public static void showArrays(int[] nums, String str) {System.out.println("===" + str + "===");showArrays(nums);}public static void showArrays(int[] nums) {for (int i = 0; i < nums.length; i++)System.out.printf(nums[i] + " ");System.out.println();}public static void main(String[] args) {int[] nums = new int[] {1,3,2,3,4,2,7,5};// int[] nums = new int[]{3,2,3};showArrays(nums, "origin");//print i-th min nubmer.for (int i = 1; i <= nums.length; i++) {System.out.println( i + " " + findKthLargest(nums, i) );}quickSortStack(nums, 0, nums.length - 1);showArrays(nums, "quickSortStack");}
}class Range {public int left;public int right;public Range(int left, int right) {this.left = left;this.right = right;}
}

轉載于:https://www.cnblogs.com/johnleo/p/quicksort_and_quickselect.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391582.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391582.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391582.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

小程序點擊地圖氣泡獲取氣泡_氣泡上的氣泡

小程序點擊地圖氣泡獲取氣泡Combining two colors that are two steps apart on the Color Wheel creates a Diad Color Harmony. This Color Harmony is one of the lesser used ones. I decided to cover it here to add variety to your options for colorizing visualizati…

leetcode 150. 逆波蘭表達式求值(棧)

根據 逆波蘭表示法&#xff0c;求表達式的值。 有效的算符包括 、-、*、/ 。每個運算對象可以是整數&#xff0c;也可以是另一個逆波蘭表達式。 說明&#xff1a; 整數除法只保留整數部分。 給定逆波蘭表達式總是有效的。換句話說&#xff0c;表達式總會得出有效數值且不存在…

WebLogic常見問題

myeclipseweblogic10的配置&#xff0c;配置成功 運行中可能失敗&#xff0c;由于weblogic10不穩定&#xff0c;重啟機器后可以使用了 web工程使用到hibernate3時可能出現問題 ClassNotFoundException: org.hibernate.hql.ast.HqlToken 參考http://blog.chinajavaworld.com/ent…

PopTheBubble —測量媒體偏差的產品創意

產品管理 (Product Management) A couple of months ago, I decided to try something new. The MVP Lab by Mozilla is an 8-week incubator for pre-startup teams to explore product concepts and, over the 8 weeks of the program, ship a minimum viable product that p…

linux-Centos7安裝nginx

首先配置linux環境&#xff0c;我這里是剛剛裝好linux&#xff0c;所以一次性安裝了一系列我需要到的環境&#xff1b; yum install pcre pcre-devel zlib zlib-devel openssl openssl-devel gd gd-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel e…

javascript原型_JavaScript原型初學者指南

javascript原型You cant get very far in JavaScript without dealing with objects. Theyre foundational to almost every aspect of the JavaScript programming language. In fact, learning how to create objects is probably one of the first things you studied when …

leetcode 73. 矩陣置零

給定一個 m x n 的矩陣&#xff0c;如果一個元素為 0 &#xff0c;則將其所在行和列的所有元素都設為 0 。請使用 原地 算法。 進階&#xff1a; 一個直觀的解決方案是使用 O(mn) 的額外空間&#xff0c;但這并不是一個好的解決方案。 一個簡單的改進方案是使用 O(m n) 的額…

elasticsearch,elasticsearch-service安裝

在Windows上安裝Elasticsearch.zip 1 安裝條件 安裝需具備java 8或更高版本&#xff1b;官方的Oracle發行版&#xff0c;只需安裝JDKElasticsearch的ZIP安裝包——安裝包地址 2 如何安裝 Elasticsearch 傻瓜式的點下一步即可&#xff0c; java 注意環境變量配置 3 如何判斷安裝…

圖表可視化seaborn風格和調色盤

seaborn是基于matplotlib的python數據可視化庫&#xff0c;提供更高層次的API封裝&#xff0c;包括一些高級圖表可視化等工具。 使用seaborn需要先安裝改模塊pip3 install seaborn 。 一、風格style 包括set() / set_style() / axes_style() / despine() / set_context() 創建正…

面向Tableau開發人員的Python簡要介紹(第3部分)

用PYTHON探索數據 (EXPLORING DATA WITH PYTHON) One of Tableau’s biggest advantages is how it lets you swim around in your data. You don’t always need a fine-tuned dashboard to find meaningful insights, so even someone with quite a basic understanding of T…

leetcode 191. 位1的個數(位運算)

編寫一個函數&#xff0c;輸入是一個無符號整數&#xff08;以二進制串的形式&#xff09;&#xff0c;返回其二進制表達式中數字位數為 ‘1’ 的個數&#xff08;也被稱為漢明重量&#xff09;。 提示&#xff1a; 請注意&#xff0c;在某些語言&#xff08;如 Java&#xf…

7、芯片發展

第一臺繼電器式計算機由康德拉.楚澤制造&#xff08;1910-1995&#xff09;&#xff0c;這臺機器使用了二進制數&#xff0c;但早期版本中使用的是機械存儲器而非繼電器&#xff0c;使用老式35毫米電影膠片進行穿孔編程。 同一時期&#xff0c;哈佛大學研究生霍華德.艾肯 要尋找…

seaborn分布數據可視化:直方圖|密度圖|散點圖

系統自帶的數據表格&#xff08;存放在github上https://github.com/mwaskom/seaborn-data&#xff09;&#xff0c;使用時通過sns.load_dataset(表名稱)即可&#xff0c;結果為一個DataFrame。 print(sns.get_dataset_names()) #獲取所有數據表名稱 # [anscombe, attention, …

如何成為一個優秀的程序員_如何成為一名優秀的程序員

如何成為一個優秀的程序員by Amy M Haddad通過艾米M哈達德(Amy M Haddad) 如何成為一名優秀的程序員 (How to be a great programmer) What sets apart the really great programmers?是什么使真正出色的程序員與眾不同&#xff1f; As we all know, great programmers buil…

pymc3使用_使用PyMC3了解飛機事故趨勢

pymc3使用Visually exploring historic airline accidents, applying frequentist interpretations and validating changing trends with PyMC3.使用PyMC3直觀地瀏覽歷史性航空事故&#xff0c;應用常識性解釋并驗證變化趨勢。 前言 (Preface) On the 7th of August this yea…

視頻監控業務上云方案解析

摘要&#xff1a;阿里云針對安防監控服務在傳統IT架構下面臨的上述問題&#xff0c;基于阿里云存儲服務&#xff0c;提供視頻監控解決方案。從2015年推出視頻監控存儲與播放解決方案以來&#xff0c;幫助大量的視頻監控企業解決了上云的過程中遇到的問題&#xff0c;針對不同的…

leetcode 341. 扁平化嵌套列表迭代器(dfs)

給你一個嵌套的整型列表。請你設計一個迭代器&#xff0c;使其能夠遍歷這個整型列表中的所有整數。 列表中的每一項或者為一個整數&#xff0c;或者是另一個列表。其中列表的元素也可能是整數或是其他列表。 示例 1: 輸入: [[1,1],2,[1,1]] 輸出: [1,1,2,1,1] 解釋: 通過重復…

爬蟲結果數據完整性校驗

數據完整性分為三個方面&#xff1a; 1、域完整性&#xff08;列&#xff09; 限制輸入數據的類型&#xff0c;及范圍&#xff0c;或者格式&#xff0c;如性別字段必須是“男”或者“女”&#xff0c;不允許其他數據插入&#xff0c;成績字段只能是0-100的整型數據&#xff0c;…

go map數據結構

map數據結構 key-value的數據結構&#xff0c;又叫字典或關聯數組 聲明&#xff1a;var map1 map[keytype]valuetype var a map[string]string var a map[string]int var a map[int]string var a map[string]map[string]string備注&#xff1a;聲明是不會分配內存的&#xff0c…

吳恩達神經網絡1-2-2_圖神經網絡進行藥物發現-第2部分

吳恩達神經網絡1-2-2預測毒性 (Predicting Toxicity) 相關資料 (Related Material) Jupyter Notebook for the article Jupyter Notebook的文章 Drug Discovery with Graph Neural Networks — part 1 圖神經網絡進行藥物發現-第1部分 Introduction to Cheminformatics 化學信息…