简体   繁体   中英

How to sort an array starting from the middle?

Considering, I have an array like this [..., n-2, n-1, n, n+1, n+2, ...]. I would like to sort it in this way [n, n+1, n-1, n+2, n-2,...] with n equals to the middle of my array.

For example:

Input:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Output:

[5, 6, 4, 7, 3, 8, 2, 9, 1, 0]

 let arrayNotSorted = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let positionMiddleArray = Math.trunc(arrayNotSorted.length / 2); let arraySorted = [arrayNotSorted[positionMiddleArray]]; for(let i=1; i <= positionMiddleArray; i++){ if(arrayNotSorted[positionMiddleArray + i] !== undefined){ arraySorted.push(arrayNotSorted[positionMiddleArray + i]); } if(arrayNotSorted[positionMiddleArray - i] !== undefined){ arraySorted.push(arrayNotSorted[positionMiddleArray - i]); } } console.log('Not_Sorted', arrayNotSorted); console.log('Sorted', arraySorted); 

What I have done works properly, but I would like to know if there is a better way or a more efficient way to do so ?

You could take a pivot value 5 and sort by the absolute delta of the value and the pivot values an sort descending for same deltas.

 var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], pivot = 5; array.sort((a, b) => Math.abs(a - pivot) - Math.abs(b - pivot) || b - a); console.log(...array); // 5 6 4 7 3 8 2 9 1 0 

You can do that in following steps:

  • Create an empty array for result.
  • Start the loop. Initialize i to the half of the length.
  • Loop backwards means decrease i by 1 each loop.
  • push() the element at current index to the result array first and the other corresponding value to the array.

 function sortFromMid(arr){ let res = []; for(let i = Math.ceil(arr.length/2);i>=0;i--){ res.push(arr[i]); res.push(arr[arr.length - i + 1]) } return res.filter(x => x !== undefined); } console.log(sortFromMid([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) [5, 6, 4, 7, 3, 8, 2, 9, 1, 0] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM