Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

selection sort algorithm in cpp

#include <iostream>

void swap(int *xp, int *yp) {
  int temp = *xp;
  *xp = *yp;
  *yp = temp;
}

void selectionSort(int arr[], int n) {
  int i, j, min_idx;
  for (i = 0; i < n - 1; i++) {
    min_idx = i;
    for (j = i + 1; j < n; j++) {
      if (arr[j] < arr[min_idx]) {
        min_idx = j;
      }
    }

    if (min_idx != i) {
      swap(&arr[min_idx], &arr[i]);
    }
  }
}

void printArray(int arr[], int size) {
  int i;
  for (i = 0; i < size; i++) {
    std::cout << arr[i] << " ";
  }
  std::cout << std::endl;
}

int main() {
  int arr[] = {64, 25, 12, 22, 11};
  int n = sizeof(arr) / sizeof(arr[0]);
  std::cout << "unsorted array: ";
  printArray(arr, n);
  std::cout << std::endl;
  selectionSort(arr, n);
  std::cout << "Sorted array: ";
  printArray(arr, n);
  std::cout << std::endl;

  return EXIT_SUCCESS;
}
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #selection #sort #algorithm #cpp
ADD COMMENT
Topic
Name
1+1 =