View Full Version : Sorting Parallel Arrays

06-11-2007, 07:51 AM
How do I modify this code so that it rearranges the letters corresponding to their original positions as they related to the numbers? Right now it just prints the letters from a-h after I sort the numbers. The original index position of 15 corresponds the index of h. So when array a is sorted in ascending order, it should display 15H instead of 15B. I can't figure it out how to swap array abc at the same time (if that's what I need to do).

var abc = "ABCDEFGH";
var a = new Array(12,23,34,65,21,37,99,15);
document.write( "Original Number Array: "+a+"<br><br> new pairs: ");

function swap( arr, x, y ) {
var temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;


for ( var f = 0; f < a.length-1; f++ ) {
var iSmallest = f;
for ( var i = f+1; i < a.length; i++ )
if ( a[i] < a[iSmallest] )
iSmallest = i;

swap( a, f, iSmallest );
for ( var i = 0; i < abc.length; i++ )
for ( var i = 0; i < a.length; i++ )
document.write( " " + a[i]+abc[i]/*this i know is wrong*/);

06-11-2007, 10:17 AM
Why not have a "2D" array and then use the built-in Array sort (`http://devguru.com/technologies/javascript/10559.asp) function?

var arr = new Array(
[12, 'A'],
[23, 'B'],
[34, 'C'],
[65, 'D'],
[21, 'E'],
[37, 'F'],
[99, 'G'],
[15, 'J']

function compareFunc(a, b){
return a[0] - b[0];

//sort it

for (var i=0; i<arr.length; i++){
alert(arr[0] + "=" + a[1]);

06-11-2007, 10:43 AM
I can't get that to work. The error console just says A is not defined.

06-11-2007, 10:52 AM
Looks like this thread is related to this thread (http://www.codingforums.com/showthread.php?t=116038). If so, then the solution should be like this:

<script type="text/javascript">

function compareFunc(a, b){ //ascending order
return a[0] - b[0];

var arr = new Array();
for (var i=0; i<26; i++){
arr[i] = [0, String.fromCharCode(i+65)];

function countLetter(letters){
letters = letters.toUpperCase();
for (var p = 0; p < letters.length; p++) {

var input = prompt("enter string", "");
var s="";
for (var i=0; i<arr.length; i++){
if (arr[i][0] != 0){ //don't display 0's
s += arr[i][1] + "=" + arr[i][0] + "\n";


06-11-2007, 03:22 PM
The output isn't sorted numerically (if I typed abbccc output should be 3=c, 2=b, 1=a).

06-11-2007, 04:46 PM
Can you post your code? When I run my code and typed abbccc, the output was:

It is sorted in ascending order. To do it the reverse, you need to change this:

function compareFunc(a, b){ //ascending order
return a[0] - b[0];

function compareFunc(a, b){ //descending order
return b[0] - a[0];

06-11-2007, 04:53 PM
Oh crap. I was kinda spaced out. My mistake! I do know the definition of ascending order, btw!

06-12-2007, 01:27 PM
Why not just swap the two arrays in parallel:


swap( a, f, iSmallest );


swap( a, f, iSmallest ); swap( abc, f, iSmallest );

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum