Tuesday, 5 May 2026

Program C++ Insertion Sort

 #include <iostream>

using namespace std;
 
int main() {
  cout << "##  Program C++ Mengurutkan Angka (Insertion Sort) ##" << endl;
  cout << "=====================================================" << endl;
  cout << endl;
 
  int i, j, n, key;
 
  // Baca angka input dari user
  cout << "Input jumlah element array: ";
  cin >> n;
  cout << endl;
 
  int arr[n];
  cout <<  "Input "<< n << " angka (dipisah dengan enter): ";
  cout << endl;
 
  for(i = 0; i < n; i++){
    cout << "Angka ke-" << i+1 <<": ";
    cin >> arr[i];
  }
 
  // Urutkan array dengan algoritma insertion sort
  for (i = 1; i < n; i++) {
    key = arr[i];
    j = i - 1;
 
    while (j >= 0 && arr[j] > key) {
      arr[j + 1] = arr[j];
      j--;
    }
 
    arr[j + 1] = key;
  }
 
  // Tampilan hasil pengurutan
  cout << endl;
  cout << "Array setelah diurutkan: ";
  for (i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
 
  return 0;
}

No comments:

Post a Comment