Skip to content
Advertisement

Sort array without any sort methods using JS [closed]

My goal is not to use any Bubble/Section/Insertion/Merge/Quick Sort—nothing built in.

I am trying to figure out how to:

let arr = [2, 8, 7, 3]

for(let i = 0; i < arr.length; i++) {
  //here I want to number use numbers as an index let's say: arr[0] is 2 right? 
  // I want to set number 2 at index 2 - 1
  //arr[1] = at index 8 - 1 
  //arr[2] = at index 7 - 1
  //arr[3] = at index 3 - 1
  //output will be :    arr [2, 3, 7, 8]
  //here index of each num   ^  ^  ^  ^
  //                         1  2  6  7

 
}

here I tried to remove empty items but I lost whole numbers.screenshot

let arr =[1,3,4,5,6]

let copyArr = [...arr]

copyArr[199] = 200
copyArr[149] = 150

console.log(copyArr)

let str = copyArr.toString().replaceAll(',','').split('')
console.log(str,)


// OUTPUT BELOW:


//copyArr:
// [ 1, 3, 4, 5, 6, <144 empty items>, 150, <49 empty items>, 200 ]

//str :
// [
//   '1', '3', '4', '5',
//   '6', '1', '5', '0',
//   '2', '0', '0'
// ] 

Advertisement

Answer

There’s no need to subtract 1. Just assign each value to the corresponding index of the result array. This will work as long as all the values are non-negative integers and there are no duplicates. You don’t have to ensure that the starting index is 0, because the step that removes all the empty values will take care of that.

After this, you can use a simple for loop to splice out all the undefined elements that were created in the gaps.

let result = [];
let arr = [2, 8, 7, 3];

for (let i = 0; i < arr.length; i++) {
  result[arr[i]] = arr[i];
}

// remove all the empty elements
for (let i = result.length-1; i >= 0; i--) {
  if (result[i] === undefined) {
    result.splice(i, 1);
  }
}

console.log(result);

See Looping through array and removing items, without breaking for loop for why the second loop counts down instead of up.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement