ใช้สองพอยน์เตอร์ ต่ำ สูง เราจะใช้พอยน์เตอร์ต่ำในตอนเริ่มต้น และตัวชี้สูงจะชี้ไปที่ส่วนท้ายของอาร์เรย์ที่กำหนด
หากอาร์เรย์ [ต่ำ] =0 แสดงว่าไม่จำเป็นต้องสลับ
หากอาร์เรย์ [ต่ำ] =1 จำเป็นต้องมีการสลับ ลดค่าตัวชี้สูงหนึ่งครั้ง
ความซับซ้อนของเวลา − O(N)
ตัวอย่าง
using System;
namespace ConsoleApplication{
public class Arrays{
public void SwapZerosOnes(int[] arr){
int low = 0;
int high = arr.Length - 1;
while (low < high){
if (arr[low] == 1){
Swap(arr, low, high);
high--;
}
else{
low++;
}
}
}
private void Swap(int[] arr, int pos1, int pos2){
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
int[] arr1 = { 0, 1, 1, 0, 1, 1 };
a.SwapZerosOnes(arr1);
for (int i = 0; i < arr1.Length; i++){
Console.WriteLine(arr1[i]);
}
}
}
} ผลลัพธ์
0 0 1 1 1 1