JavaScript - Bubble And Selection Sort
Basically what I have here in the following code is 15 random numbers that I am supposed to use the bubble and selection sort algorithm to sort. How can I go about getting the numbers to be sorted using selection sort I have already done the bubble. Thanks
Code: <html> <body> <script language ="javaScript"> var array = new Array(15); function genNumbers(listbox){ var i; for(i= 0; i < array.length; i++) { array[i] = Math.random()*15; array[i] = Math.round(array[i]); } updateList(listbox); } function sortNumbers(listbox) { var x, y, holder; for(x=0; x < array.length; x++) { for(y=0; y< (array.length-1); y++){ if(array[y] > array[y+1]){ holder = array[y+1]; array[y+1] = array[y]; array[y] = holder; } } } updateList(listbox); } function updateList(listbox) { var i; for(i = 0; i< array.length; i++){ if(listbox.options[i] == null) { listbox.options[i] = new Option(array[i]); } else{ listbox.options[i].text = array[i]; } } } </script> <form> <center> <select name = "ranlist" size "10" style = "width: 100px"> </select> <br><br><br> <input type = "button" value = "Generate" onClick = "genNumbers(this.form.ranlist);"> <input type = "button" value = "Bubble Sort" onClick = "sortNumbers(this.form.ranlist);"> </form> </body> </html> Similar TutorialsI have been working on the code for an alpha sort file and have become stumped. I need to incorporate both an insertion sort & selection sort method into my code before it will run. I attached the file I have been working on and it runs on Bluej with Java JDK. I would apretiate if you could take a look at it. If you would prefer not to download my file I have posted my code that I have been working on below. I am not familiar with the structure of an insertion sort or a selection sort mothod. I also am not clear on the point in which these methods would need to be placed in the file. Code: import java.io.*; import java.util.*; public class Words { ArrayList<String> words; public Words() { words = getData("wordlist.txt"); } public void displayWords() { for(int i=0; i<words.size(); i++) { System.out.println(words.get(i)); } } public ArrayList<String> getData(String filename) { ArrayList<String> list = new ArrayList<String>(); File myFile = new File(filename); if(myFile.exists() && myFile.length()>0) { try { BufferedReader in = new BufferedReader( new FileReader(myFile) ); String word = in.readLine(); while( word != null ) { list.add(word); word = in.readLine(); } } catch( Exception e ) {} } return list; } } Hi, OK, I know a bubble sort is very inefficient for sorting values but I have to do it as part of some coursework. I have the code working, i.e. it produces a sorted list of numeric values but the process of sorting the values is wrong. Below is my complete script. Code: <HTML> <HEAD> <TITLE> A program to sort an array using a bubble sort </TITLE> <SCRIPT> /*A function to sort an array. Function takes an array of numbers as an argument. Function returns a new array with the same elements as the argument array, sorted into ascending order*/ function bubbleSort(arrayToSort) { // declare and initialise a variable to hold the length of the argument array var length = arrayToSort.length; //declare an array to be returned by the function var returnArray = new Array(length); //copy each element of the argument array to the return array for (var i = 0; i < length; i = i + 1) { returnArray[i] = arrayToSort[i]; } // PLACE YOUR CODE FOR THE FUNCTION HERE /* */ for (var j = 0; j < returnArray.length - 1; j = j + 1) { for (var k = j + 1; k < returnArray.length; k = k + 1) if (returnArray[j] > returnArray[k]) { var temp; temp = returnArray[j]; returnArray[j] = returnArray[k]; returnArray[k] = temp; document.write('Array after each swap ' + returnArray + '<BR>') } } return returnArray; } /* a function for testing the bubbleSort() function. Function assigns an array to a variable Displays elements of unsorted array in order Invokes bubbleSort() function with the array as the argument Displays elements of sorted array in order Function takes no arguments. Function returns no value.*/ function bubbleTest() { var unsortedArray; //array to accept numbers to be sorted var sortedArray; //array to show sorted numbers // the array of values to be sorted unsortedArray = [4,3,2,1]; // TO DO TASK 3 (iv) // PLACE YOUR FUNCTION CODE HERE /*Write out the array 'unsortedArray'*/ document.write('A program to sort a series of numbers using the Bubble Sort method.' + '<BR>' + 'Unsorted array ' + unsortedArray + '<BR>'); /*Assign the results of the 'bubbleSort' function to the array 'sortedArray'*/ sortedArray = bubbleSort(unsortedArray); /*Write out the array 'sortedArray'*/ document.write('Sorted array ' + sortedArray + '<BR>'); /* The arrays below are for use in Task 4 (iii) and Task 5(iii) and can be ignored in Task 3 DATA SET 1 [8,4,6,2,10,5,3,7,1,9] DATA SET 2 [1,5,2,8,6,7,10,9,4,3] DATA SET 3 [ 6,3,8,7,2,9,10,4,5,1] DATA SET 4 [7,5,2,10,6,8,4,3,9,1] DATA SET 5 [9,4,1,10,5,2,3,8,7,6] */ } /*Test area for bubbelSort array*/ //var unsortedArray = [9,7,2,10,1,4,8,6,5,3]; //Test arguments //bubbleSort(unsortedArray); // invoke bubbleTest() to test the bubbleSort() function bubbleTest(); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> OK, the problem is that on after the first pass, the numbers should be as follows: 3,2,1,4 The biggest number always ends up in it's place after each pass. My code above outputs the numbers after the first pass: 3,4,2,1 You will notice it is probably an inefficient way of writing the code. We have to only use code we have learnt Sorry for the long post!! Hi this is an assignment, ive been on it all night. I have done the bubble sort function and have to modify it. I work out that if i could stop the amount of times it loops it would make it more efficient. To do this is would need to stop the loop when no swaps have been made on the full array.lenght-1. i have tried using booleans, false and true on the amount of swaps using a while loop instead of my first for loop, however it only loops nine times...ie only covering the array once,hence does not swap the full array. so i tried leaving in the for loop that instructs it to loop for the full array. length. I have also tried using if... else at different positions within my function please i need some guidance, im going to pull my hair out i can see what need in my head just cant get it. Plus i am very very new to this My simple objective is.... to set a flag to stop the loop when there have not been any swaps for the duration of the array. length-1, hence the array is now organised and to display the amount of loops taken. Heres the part that ive been changing and my latest attempt which is using if, however it still loops for 90 loops. Code: var temp; ;// varible to hold temporay value, var numberOfLoops = 0 swap = true if (swap = true) { for (var count = 0; count < returnArray.length; count = count +1)// sets any array lenght to be used and the number of passes as lenght of array for (var i = 0; i < returnArray.length-1; i = i + 1)// starting postion and what elements should be covered minus one pass less than the arrray { if ((returnArray[i]) > (returnArray[i+1])) { temp = returnArray[i+1]; //hold second value in temp var returnArray[i+1] = returnArray[i];// replace value second value with first value returnArray[i] = temp;//replace first value with value held in temp var swap = true } else { swap = false } numberOfLoops = numberOfLoops + 1 } } window.alert('number of loops taken is ' + numberOfLoops) return returnArray My bubble sort function als0 worked fine showing 90 loops each time...until changed it Hi Everyone, I am working on a piece of pseudocode for an assignment and as I am new to Javascript, I would like some confirmation I am on the right track with the code. Algorithm selectionSort Pre a= an Array of values n= number of items in Array Post a has been sorted in descending ordered from highest to lowest value Code: for i = 0 to n-1 max = i for j = 0 to n-1 if a[j]>a[i-1] max = j end if endfor temp = a[j] a[j] = a[j-1] a[j-1]=temp endfor All of the research I have found has only shown ascending order formulas, so if I am wrong with my if statement and the temp statement and they should i+1 and a[j+1] can you please give a shake of the head; that way I can read my research further and edit my work. If I am on track a nod of the head is a big encouragement. Regards BP I enclose code that should work. What to change that this code will work. I used prototype.js hi On my map, I have several markers, see my code: Code: <script language="JavaScript" type="text/javascript"> function load() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); var locationIcon = new GIcon(G_DEFAULT_ICON); //both images must be the same size locationIcon.image = "images/google-pin.png"; locationIcon.shadow = "images/google-pin-shadow.png"; locationIcon.iconSize = new GSize(90, 70); locationIcon.shadowSize = new GSize(90, 70); markerOptions = { icon:locationIcon }; map.setCenter(new GLatLng(51.3992613899243,-1.32983778443008), 8); // center point between the 2 map.addOverlay(new GMarker(new GLatLng(51.4769752333875,-2.53517458867092), markerOptions)); //BS16 3HH map.addOverlay(new GMarker(new GLatLng(50.8391656924497,-0.154312843280554), markerOptions)); // BN1 5PT map.addOverlay(new GMarker(new GLatLng(50.8340528225749,-0.259947032613667), markerOptions)); // BN43 6NZ map.addOverlay(new GMarker(new GLatLng(51.5168824045344,-2.6926718990779), markerOptions)); // BS11 9YQ map.addOverlay(new GMarker(new GLatLng(50.954582894922,-0.145016932400171), markerOptions)); // RH15 9LR } } //51.514925,-0.150118 W1U 1JQ //51.497593,-0.164806 SW3 1NQ </script> I would like to add an info bubble for each of my markers, would I add this piece of code somewhere within my code: Code: GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml("<table width='215'><tr><td><a rel="nofollow" target='_blank' href='http://www.lcls.org/'>Lewis & Clark Library System</a></td></tr><tr><td><img src='http://www.lcls.org/images/galleries/tour/01-BuildingFromLot.JPG' border='0' width='195px' height='95' /></td></tr><tr><td>425 Goshen Road<br />Edwardsville,IL 62025<br />618-656-3216</td></tr></table><br /><a rel="nofollow" target='_blank' href='http://maps.google.com/maps?q=425 Goshen Road%20Edwardsville,%20IL'>Directions</a>"); }); A dynamically-generated div pops up with absolute positioning, prompting user radio-button selection. div is selected and focused, and triggers onblur event to remove it from DOM. Clicking one of the radio buttons within the div should not remove the div from the DOM. problem: clicking radio button removes the div from the DOM even though the radio button is inside the div and even though clicking the radio button triggers onclick event to cancelBubble. I'm about to post this, and thinking that I should modify the blur event to remove the div only if the click event is outside of its coords... (...terribly sleep-deprived, lol) Since I've already prepped this post..., any thoughts / suggestions? Sample code: Code: var items = ['carrots', 'bananas', 'apples'], fragment = null, item = null; if (items.length > 0) { fragment = <div id="AddItemSelector" onblur="Cancel_AddNewItem();"><div name="title">Select Item:</div>'; do { item = items.shift(); fragment += '<div><input name="radNewItem" type="radio" value="' + item + '" onclick="Click_NewItem(event)">' + item + '</div>'; } while (items.length > 0); fragment += '<div><input type="button" value="Cancel" onclick="Cancel_AddNewItem();"><input type="button" value="Select" onclick="Select_AddNewItem();"></div></div>'; $(blahblah).after(fragment); $('#AddItemSelector').select().focus(); } items = null; fragment = null; item = null; ... function Click_NewItem(Event) { Event.cancelBubble = true; } function Cancel_AddNewItem() { $('#AddItemSelector').remove(); } I found this beautiful fade-in/fade-out jQuery pop-up bubble and all I need to know is how to make the bubble animate on window.onload. If there's a better pop-up bubble than this that someone knows of offhand, that'd be great too. I haven't tested this one out and am a little wary about potential problems that the non-animated part of the bubble may or may not present. All I want to have happen is, when you visit the site, a div automatically fades in and stays near the top of the page for a minute to guide viewers to a specific area of the site, and then fades out. Thanks for any help!! Much appreciated. I've been trying for some time now to create some code which dynamically adds markers to a google map. I've now managed this but I still have a slight problem I think with the javascript side of things. I've included a snippet of the code which shows 2 markers on the map. They should be 2 different markers but they are the same, and the contents of the popup bubble should be each individual postcode, but they both show the same postcode. Does anyone have any ideas? Thanks Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Geocoding UK Postcodes with Google APIs Demo</title> <style type="text/css"> html { height: 100%; } body { margin: 0; padding: 0; height: 100%; } #map { width: 100%; height: 100%; z-index:1; } </style> <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAAQJTCOfFBzEZfb0xYTu1h_BR0_9owy9VLLEJCKI_ZedHr-0NdXxQd9Q8sR1hC7s4PNGNVmIaTUQvspA" type="text/javascript"></script> <script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAQJTCOfFBzEZfb0xYTu1h_BR0_9owy9VLLEJCKI_ZedHr-0NdXxQd9Q8sR1hC7s4PNGNVmIaTUQvspA" type="text/javascript"></script> <script type="text/javascript"> //<![CDATA[ var icon2 = new GIcon(); icon2.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"; icon2.shadow = "http://www.google.com/mapfiles/shadow50.png"; icon2.iconSize = new GSize(32, 32); icon2.shadowSize = new GSize(37, 34); icon2.iconAnchor = new GPoint(16, 32); icon2.infoWindowAnchor = new GPoint(16, 0); var icon3 = new GIcon(); icon3.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png"; icon3.shadow = "http://www.google.com/mapfiles/shadow50.png"; icon3.iconSize = new GSize(32, 32); icon3.shadowSize = new GSize(37, 34); icon3.iconAnchor = new GPoint(16, 32); icon3.infoWindowAnchor = new GPoint(16, 0); var localSearch = new GlocalSearch(); function initialize() { if (GBrowserIsCompatible()) { map = new GMap(document.getElementById("map")); map.setCenter(new GLatLng(55.100651, -4.664941), 6); } } function createMarker(point2,html) { var marker2 = new GMarker(point2,icon2); GEvent.addListener(marker2, "click", function() { marker2.openInfoWindowHtml(html, { noCloseOnClick: true }); }); return marker2; } function createMarker2(point3,html) { var marker3 = new GMarker(point3,icon3); GEvent.addListener(marker3, "click", function() { marker3.openInfoWindowHtml(html, { noCloseOnClick: true }); }); return marker3; } //]]> </script> </head> <body> <div id="map"><script type="text/javascript">document.write(initialize())</script></div> <script type="text/javascript"> var thetext = 'LL58 8HU' localSearch.execute("LL58 8HU, UK"); localSearch.setSearchCompleteCallback(null, function() { map.addOverlay(createMarker(new GLatLng(localSearch.results[0].lat,localSearch.results[0].lng),thetext)); }); </script> <script type="text/javascript"> var thetext2 = 'RG4 6UT' localSearch.execute("RG4 6UT, UK"); localSearch.setSearchCompleteCallback(null, function() { map.addOverlay(createMarker2(new GLatLng(localSearch.results[0].lat,localSearch.results[0].lng),thetext2)); }); </script> </body> </html> Hi I'm working on displaying a list of events on my site and need to display them in ascending order. i've got an xml document that looks like this(with multiple events obviously, i've just put one here): Code: <EventList> <Event> <Title>title example</Title> <myDescription>description example</myDescription> <myLink>http://www.example.com</myLink> <dayDate>10</dayDate> <monthDate>5</monthDate> <yearDate>2010</yearDate> <EventPic>Event.gif</EventPic> </Event> </EventList> Then on my html page, I have this javascript: Code: <script type="text/javascript"> if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else // Internet Explorer { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET","Events.xml",false); xhttp.send(""); xmlDoc=xhttp.responseXML; var jDate=new Date(); var jYear=jDate.getFullYear(); var jYearStr=jYear.toString(); var jMonth=jDate.getMonth()+1; var jMonthStr=jMonth.toString(); var jDay=jDate.getDate(); var jDayStr=jDay.toString(); var currentDate=jYearStr+jMonthStr+jDayStr; document.write("<div>"); var x=xmlDoc.getElementsByTagName("Event"); for (i=0;i<x.length;i++) { var theMonthDate=x[i].getElementsByTagName("monthDate")[0].childNodes[0].nodeValue; var theDayDate=x[i].getElementsByTagName("dayDate")[0].childNodes[0].nodeValue; var theYearDate=x[i].getElementsByTagName("yearDate")[0].childNodes[0].nodeValue; var theDate=theYearDate+theMonthDate+theDayDate; if (theDate>=currentDate) { document.write("<br>"); document.write("<a href='"); document.write(x[i].getElementsByTagName("myLink")[0].childNodes[0].nodeValue); document.write("'>"); document.write(x[i].getElementsByTagName("Title")[0].childNodes[0].nodeValue); document.write("</a>"); document.write("<br>"); document.write(x[i].getElementsByTagName("myDescription")[0].childNodes[0].nodeValue); document.write("<br>"); document.write(x[i].getElementsByTagName("monthDate")[0].childNodes[0].nodeValue); document.write("/"); document.write(x[i].getElementsByTagName("dayDate")[0].childNodes[0].nodeValue); document.write("/"); document.write(x[i].getElementsByTagName("yearDate")[0].childNodes[0].nodeValue); document.write("<br>"); } } document.write("</div>"); </script> Can anyone help me with sorting this? So far I have it displaying only events that are occuring after the present date(currentDate). How would I go about displaying them so that the events displayed will be in the order of the earliest date displaying first? Thanks so much, Alex Hello JS experts: I simply want to sort this output by date: Code: document.write(x[i].getElementsByTagName("cdate")[0].childNodes[0].nodeValue); Why can't I simply just do this? Code: document.write((x[i].getElementsByTagName("cdate")[0].childNodes[0].nodeValue).sort()); XML : Code: <item> <number>10-0057-FW</number> <title>Supervisory Contract Specialist</title> <link>http://test.usaid.com/careers/TESTgscover.html#1826296</link> <guid>http://test.usaid.com/careers/TESTgscover.html#1826296</guid> <description>10-0057-FW, Grade: GS-1102-15, Office: OAA, Opening Date: 02/26/10, Closing Date: 03/09/10, USAID Employees Only</description> <opp>1826296</opp> <office>OAA</office> <grade>SS-1102-15</grade> <odate>02/26/10</odate> <cdate>03/09/10</cdate> <eligibility>Employees Only</eligibility> <pubDate>Fri, 26 Feb 2010 09:35:42 -0500 </pubDate> </item> Partial JS: Code: var x=xmlDoc.getElementsByTagName("item"); for (i=0;i<x.length;i++) { . . . document.write(x[i].getElementsByTagName("cdate")[0].childNodes[0].nodeValue); document.write("</td><td>"); . . . I have a status page on my website, but I have multiple servers, and they cramp up the one page. I was wondering if it was possible if I could have a link that says "CSS Server Status" and it drops down with the code for the CSS server, and say for "SAMP Server Status" drops down with the code/html for the samp server. I haven't a clue about Javascript, so as much help as possible would be appretiated. I already have a sort function that but wish to provide my users with the ability to specify custom sorts - days of the week, months etc. Assuming that I have a function that will return day of week (ie 'Mon' = 0, "Tue" = 1, "Wed" = 2 ... etc) can anyone show me how I would incorporate this into a sort routine? Many thanks in advance should you respond to this. I check the web and they only show you how to sort the whole array. I would like to be able to sort the subset of the 2D array. Here's my array. Code: var myArray=new Array( new Array("af","ad","az","ab"), new Array("bc","bd","bg","bb","bx"), new Array("cf","ck","ca","cv","co"), new Array("dd")); How would I sort the sub array independently. So only the a's together, then only the b's together, etc. thanks http://jsfiddle.net/FZ44M/3/ Thats my jsfiddle. I'm trying to get the gallerynav to sort the thumbnails based on their class. It does not work at all. I've gone over line by line but I can't see the mistake. When I run JSLink i get the error: Error: Problem at line 37 character 14: Cannot set property 'first' of undefined Implied global: $data 13,14, arr 14,15,25, jQuery 28, $ 30 Unused variable: read_button 30 "$", r 32 "read_button" I appreciate any help. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script> window.onload = function(){ document.getElementById("t").innerHTML = "<table border='1' id='myTable'>" + "<tr><td>" + names.join("<tr><td>") + "</td></tr>" + "</table>"; } var names = ["Marble","Jarque","Dino","Pineapple"]; function abc(){ if(document.getElementById('myTable').rows[0].cells[0].innerHTML==names[0]){names.sort()} else if(document.getElementById('myTable').rows[0].cells[0].innerHTML==names[2]){names.sort().reverse()} else {names.sort()} document.getElementById("t").innerHTML = "<table border='1' id='myTable'>" + "<tr><td>" + names.join("<tr><td>") + "</td></tr>" + "</table>"; } </script> </head> <body> <div id="t"></div> <input type="button" value="sort" onclick="abc()" /> </body> </html> First time sort: no problem But when it comes to the blue-highlighted parts It cannot do the sort().reserve() What's wrong with the codes? We list our branches on our webpage, but I want people to be able to search for the nearest ones. This is the form I built as a place holder... but I'm sure I need a "little something" to go along with it. ha ha ha. Code: <form class="login">   <label class="white"><b>Zip Code</b><br />   <input name="zip" type="text" maxlength="5" size="10"/> </label> <br /><br /> <label>   <input type="submit" name="submit" id="submit" value="Go!" class="btn" /> </label> </form> I would like to sort them in order of closest to furthest (or even just display the top 5)... where would I find something like that? I seem to be having a difficult time with my searches in google and otherwise. Anyone have any ideas? Hello, I have the following script, but I'd like to sort each nested array before it is written. How can I do this? I've tried putting Games.sort(); and Games[0].sort(); in different places, but it never seems to work. Code: var Games = new Array(); //PS3 Games[0] = new Array(); Games[0][0] = "ps3list"; Games[0][1] = "Uncharted: Among Thieves"; Games[0][2] = "Prince of Persia"; Games[0][3] = "Saboteur"; Games[0][4] = "Assassins Creed"; //Wii Games[1] = new Array(); Games[1][0] = "wiilist"; Games[1][1] = "Wii Play"; Games[1][2] = "Mario Party 8"; Games[1][3] = "Okami"; Games[1][4] = "Wii Sports"; function loadGames(){ for (i = 0; i < Games.length; i++) { var list = "<ul>"; for (j = 1; j < Games[i].length; j++) { list += "<li><input type = 'checkbox' class='checkbox' name = '" + Games[i][j] + "' />" + Games[i][j] + "</li>"; } list += "</ul>" document.getElementById(Games[i][0]).innerHTML = list; } } Hello, I have the following object: Code: var layers = { photo1 : { index : 1, xPos : 63, yPos : 48, angle : 0 }, background : { index : 0, xPos : 278, yPos : 163, angle : 0 } } How can I sort the objects by the index property? Code: for(var layer in layers.sort(???)) { } Thx Very Much! My problem is in the drop down menus for site names, we have hundreds of sites and unfortunately the menu is not sorted 0-1 then A-Z and I would love it to be sorted like that. I have tried to do my homework and understand java / javascript but I just can't stand it and I feel it is too complicated for me. The good news is I used to be a good ASP/vbscript programmer about 12 years ago so I have the "common sense" of understanding how to apply something similar on other pages, because I have lots of drop down menus that I need to sort. I need your help in the attached file please. I need someone to simply highlight for me where in the javascript is fetching the site names from the DB and what needs to be added to sort them. Please identify it inside the file by either different color or bold font. Once I see it i will be able to figure out how to apply it in general to the other menus in the other pages. Thank you in advance. |