Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eugene0707/03d321e535aef08562f29f01b88a36b2 to your computer and use it in GitHub Desktop.
Save eugene0707/03d321e535aef08562f29f01b88a36b2 to your computer and use it in GitHub Desktop.
Сортировка 0/1
var total_elements=11; // Всего элементов в массиве
var initial_array=Array.apply(null, {length: total_elements}).map(Function.call, Math.random).map(Math.round); // Изначальный массив для контроля. Массив в сортировке не участвует
var sorted_array=initial_array.slice(); // Массив, который сортируем
// Вспомогательные переменные
var count_0=0, count_1=0;
var half=Math.trunc(total_elements/2);
var is_odd=(total_elements % 2==1) ? true : false;
for (var i=0;i<total_elements;i++) {
if (i<half) {
if (sorted_array[i]==0) {++count_0} else {++count_1};
if (sorted_array[total_elements-i-1]==0) {++count_0} else {++count_1};
}
if (is_odd && (i==half)) {
if (sorted_array[i]==0) {++count_0} else {++count_1};
if (count_0 > count_1) {
sorted_array[i]=0;
--count_0;
} else {
sorted_array[i]=1;
--count_1;
}
}
if (i>=half) {
if (count_0>0) {
sorted_array[i-half]=0;
--count_0;
} else {
if (count_1>0) {
sorted_array[i-half]=1;
--count_1;
}
}
if (count_1>0) {
sorted_array[total_elements-(i-half)-1]=1;
--count_1;
} else {
if (count_0>0) {
sorted_array[total_elements-(i-half)-1]=0;
--count_0;
}
}
}
}
// Вывод консоли для контроля результата
console.log(count_0); // должно быть = 0
console.log(count_1); // должно быть = 0
console.log(initial_array);
console.log(sorted_array);
console.log(eval(initial_array.join('+'))); // контрольная сумма единиц
console.log(eval(sorted_array.join('+'))); // -----------//------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment