Bubble sort, quick sort, array de-weight

Source: Internet
Author: User

Bubble Sort

Bubble sort is to compare the adjacent two numbers each time, (from small to large) if the front number is larger than the number behind, then exchange, otherwise do not exchange;

var arr = [11,12,14,9,10,99,22,7]; Array.prototype.bubbleSort = function () {for (var i = 0; i < this.length; i++) {//First-layer loop://Total number of rounds for (var j = 0; j < th Is.length-i-1; J + +) {//Second layer loop://First round comparison after the largest swap to the end//second round comparison after the second largest swap to the end//... if (This[j] > This[j+1]) {var temp = this[j];this[j] = this[j+ 1];THIS[J+1] = temp;}}}} Arr.bubblesort (); Console.log (arr);//[7, 9, 10, 11, 12, 14, 22, 99]

  

Quick Sort(1) The Selection datum (2) is less than the base number exists on the left, greater than the existence of the right (3) recursive entire function
function QuickSort (arr) {if (arr.length <= 1) return arr;//Select benchmark var index = Math.floor (ARR.LENGTH/2); var pivot = ARR.SPL Ice (index,1);//intercept the array, the original array changes console.log (pivot);//judgment, greater than Indexarr put to the right, less than put left var = [],right = [];for (var i = 0; i < arr. Length i++) {if (Arr[i] < pivot[0]) {Left.push (arr[i]);} Else{right.push (Arr[i]);}} Recursive call function return QuickSort (left). Concat (Pivot,quicksort);} var arr = [11,22,14,9,89,66];console.log (QuickSort (arr));
array de-weight

The indexof of the array is mainly applied to the array method.

Array.prototype.delWeight = function () {var newArr = [];for (var i = 0; i < this.length; i++) {if (Newarr.indexof (This[i]) = =-1) {Newarr.push (this[i]);}} return NEWARR;}

Bubble sort, quick sort, array de-weight

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.