• 排序算法


    <script type="text/javascript">
    	//从小到大
    	var arr = [12, 3, 56, 45, 25, 8, 6, 5, 40];
    	//冒泡排序(时间复杂度n2,空间复杂度1,稳定)
    	var temp;
    	for(var i = 0; i < arr.length ; i++)            {
    	    for(var j = 0; j < arr.length; j++)             {
    				if(arr[j] > arr[j + 1]) {
    					temp = arr[j];
    					arr[j] = arr[j + 1];
    					arr[j + 1] = temp;
    					}
    				}
    			}
    		for(var i = 0; i < arr.length; i++)             {
    				console.log(arr[i])
    			}	
    </script>
    
    <script type="text/javascript">
    			//从小到大
    			var arr = [12, 3, 56, 45, 25];
    			//选择排序(时间复杂度n2,空间复杂度1,不稳定)
    			var temp;
    			var min;
    			for(var i = 0; i < arr.length; i++) {
    				min = i;
    				for(var j = i + 1; j < arr.length; j++) {
    					if(arr[min] > arr[j]) {
    						min = j;
    					}
    				}
    				temp = arr[min];
    				arr[min] = arr[i];
    				arr[i] = temp;
    			}
    			for(var i = 0; i < arr.length; i++) {
    				console.log(arr[i]);
    			}
    		</script>
    
    <!DOCTYPE html>
    <html>
    
    	<head>
    		<meta charset="UTF-8">
    		<title></title>
    		<script type="text/javascript">
    			var arr = [12, 3, 56, 45, 25, 5, 36, 95, 62];
    			quickSort(arr);
    			for(var i = 0; i < arr.length; i++) {
    				console.log(arr[i]);
    			}
    
    			function quickSort(array) {
    				function sort(low, high) {
    					var i = low;
    					var j = high - 1;
    					var flag = array[low];
    					if((high - low) > 1) {
    						while(i < j) {
    							for(; i < j; j--) {
    								if(array[j] < flag) {
    									array[i++] = array[j];  //a[i] = a[j]; i += 1;
    									break;
    								};
    							}
    							for(; i < j; i++) {
    								if(array[i] > flag) {
    									array[j--] = array[i];
    									break;
    								}
    							}
    						}
    						array[i] = flag;
    						sort(0, i - 1);
    						sort(i + 1, high);
    					}
    				}
    				sort(0, array.length);
    				return array;
    			}
    		</script>
    	</head>
    
    	<body>
    	</body>
    
    </html>
    
  • 相关阅读:
    Python 集合
    Python sorted()
    CodeForces 508C Anya and Ghosts
    CodeForces 496B Secret Combination
    CodeForces 483B Friends and Presents
    CodeForces 490C Hacking Cypher
    CodeForces 483C Diverse Permutation
    CodeForces 478C Table Decorations
    CodeForces 454C Little Pony and Expected Maximum
    CodeForces 313C Ilya and Matrix
  • 原文地址:https://www.cnblogs.com/sakura-sakura/p/6678664.html
Copyright © 2020-2023  润新知