This version has three separete files; javascript, html, and css. In this version, the javascript is written with "use strict".
HTML File:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel ="stylesheet" type = "text/css" href = "style.css" />
<script type ="text/javascript" src ="quicksort.js"></script>
</head>
<body>
<div id="wrapper">
<div id ="innerWrapper">
<h2>This is a QuickSort project in JavaScript</h2>
<div id="qsDataOrg">
<p> The list of numbers to be sorted </p>
</div>
<div id="qsDataAns">
<p> Here is the sorted list</p>
</div>
</div>
</div>
</body>
</html>
CSS File
body {
text-align:center;
font-family:"arial",verdana,sans-serif;
color: gray; /* gray */
background-color: #f2f2f2;
}
#wrapper{
margin: 0 auto;
width: 900px;
text-align: left;
/*outline-style: solid;*/
/*outline-color: blueviolet;*/
background: white /*#f2f2f2;*/
}
#innerWrapper{
/*outline-style: solid;*/
/*outline-color: blueviolet;*/
margin-left: 20px;
}
/* quicksort style */
#qsDataOrg, #qsDataAns{
color: gray;
}
JavaScript File
"use strict"
function QuickSort() {
this.qsData = [];
this.nElem = 0;
}
QuickSort.prototype.insert = function(val) {
this.qsData[this.nElem] = val;
this.nElem++;
};
QuickSort.prototype.numOfElement = function() {
return this.nElem;
}
QuickSort.prototype.display = function(id) {
var qsdOrg = document.getElementById(id);
for (var i = 0; i < this.nElem; i++ ) {
qsdOrg.appendChild(document.createTextNode(this.qsData[i]));
qsdOrg.appendChild(document.createTextNode(" "));
}
};
QuickSort.prototype.sort = function (left, right) {
// base case is: (right-left <= 0), omitted in code
if ((right - left) > 0) {
var pivot = this.qsData[right];
var px = this.partition(left, right, pivot);
this.sort(left, px - 1);
this.sort(px + 1, right);
return;
}
};
QuickSort.prototype.partition = function(left, right, pivot) {
var temp = right;
var flag = true;
while (flag) {
while (this.qsData[left] < pivot) {
left++;
}
while ((right > 0) && (this.qsData[--right] > pivot)) {
}
if (left < right) {
this.swap(left, right);
left++;
} else {
flag = false;
}
}
this.swap(left, temp);
return left;
};
QuickSort.prototype.swap = function(x , y) {
var temp = this.qsData[x];
this.qsData[x] = this.qsData[y];
this.qsData[y] = temp;
};
// becuase the document has to be loaded, before script runs,
// need window.onload. otherwise getElementBy stuff will return null
window.onload = function(){
var a = [2,41,15,93,23,5,63,10,4,43];
var qs = new QuickSort();
for (var i = 0; i < a.length; i++) {
qs.insert(a[i]);
}
//document.write("<br />"); <<< this wipes out display
// including "qsDataOrg" and gave me the null error for qsDataOrg.
qs.display("qsDataOrg");
qs.sort(0, qs.numOfElement() - 1);
qs.display("qsDataAns");
}
No comments:
Post a Comment