JavaScript實現快速排序(自已編寫)

來源:互聯網
上載者:User

簡述
用到javascript的排序一組數字,js沒有直接的數字比較的函數可以調用,所以自己寫了一個快速排序
知識點:
1. Regex提取正負數位string
2. str 轉數字 放回列表
3. js的對象Sort類的聲明及定義
4. Sort類建構函式、成員函數定義方式(prototype)
5. 快速排序演算法
代碼

複製代碼 代碼如下:<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />.
<html>
<title>Quick Sort</title>
<head>
<script type = "text/javascript">
/*************Get Number From Input***********/
function getNumList(){
var result = "";
var nums = document.getElementById('numbers').value;
var reg = /([-][1-9][0-9]*)|([1-9][0-9]*)/g;
var numStrList = nums.match(reg);
var numList = new Array();
if(numStrList != null){
for(var i = 0;i < numStrList.length;i++){
var intNumber = parseInt(numStrList[i]);
numList.push(intNumber);
}
}
return MainProgram(numList);
};

/*****************Main*************************/
function MainProgram(numList){
var sort = new Sort(numList);
var sortedList = sort.getSortedList();
if(sortedList == null)
document.getElementById('result').innerHTML = "WRONG INPUT";
else{
document.getElementById('result').innerHTML = sortedList.join(',');
}
}

/**************Sort Class***********************/
var Sort = function(list){
this.resultList = list;
};

Sort.prototype.Partition = function(start,end){
var baseValue = this.resultList[start];
var basePos = start;
for(var j = start + 1;j <= end;j++){
if(baseValue > this.resultList[j]){
basePos++; //move the base position
this.Swap(basePos,j);
}
}
// move the base value to the correct place , before are smaller , behind are bigger
this.Swap(start,basePos);
return basePos;
}

Sort.prototype.QuickSort = function(start,end){
if(start < end){
var basePos = this.Partition(start,end);
this.QuickSort(start,basePos - 1);
this.QuickSort(basePos + 1, end);
}
};

Sort.prototype.Swap = function(pos1,pos2){
var temp = this.resultList[pos1];
this.resultList[pos1] = this.resultList[pos2];
this.resultList[pos2] = temp;
}

Sort.prototype.getSortedList = function(){
this.QuickSort(0,this.resultList.length - 1);
return this.resultList;
};

</script>
</head>
<body>
<B> Quick Sort</B>
<br>
<br>
<input type= "text" id = 'numbers' value = '' />
<input type = 'button' value = "exec" onclick = 'getNumList()'/>
<br>
<br>
<B>SORTED LIST: <B> <b id = 'result'></b>
</body>
</html>

輸出:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.