본문 바로가기
알고리즘/Codewars

[Codewars] Sort the odd (6 kyu) / JavaScript

by fluss 2023. 1. 11.

https://www.codewars.com/kata/578aa45ee9fd15ff4600090d

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Task

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Examples

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

코드

function sortArray(array) {
  for(let i = 0; i < array.length; i++){
    if(array[i] % 2 == 1 || array[i] * -1 % 2 == 1){
      for(let j = i; j < array.length; j++){
        if((array[j] % 2 == 1 || array[j] * -1 % 2 == 1) && array[i] > array[j]){
          let temp = array[i];
          array[i] = array[j];
          array[j] = temp;
        }
      }
    }
  }
  return array;
}

댓글