Lila25mila
Feb. 27, 2019, 5:24 p.m.

Selection sorting algorithm

The selection sort algorithm starts by comparing the first two elements of an array and replacing them if necessary. For example, if you want to sort the elements of an array in ascending order and if the first element is greater than the second, you need to swap the elements. But, if the first element is less than the second, the elements remain in their sequence. Then again the first element and the third element are compared and swapped if necessary. This process continues until the first and last element of the array is compared. This completes the first sort selection step.


If there are n elements to sort, the process mentioned above should be repeated n-1 times to get the desired result. To improve performance in the second step, the comparison starts from the second element, because after the first step, the desired number is automatically placed in the first one. Similarly, in the third step, the comparison starts from the third element, and so on. In the case of sorting in ascending order, the smallest element will be first, and in the case of sorting in descending order, the largest element will be first.

Consider in the figure the operation of the sorting algorithm by the selection method.

C program to sort items using selection sort algorithm
  1. #include <stdio.h>
  2. int main()
  3. {
  4. int data[100],i,n,steps,temp;
  5. printf("Enter the number of elements to be sorted: ");
  6. scanf("%d",&n);
  7. for(i=0;i<n;++i)
  8. {
  9. printf("%d. Enter element: ",i+1);
  10. scanf("%d",&data[i]);
  11. }
  12. for(steps=0;steps<n;++steps)
  13. for(i=steps+1;i<n;++i)
  14. {
  15. if(data[steps]>data[i])
  16. /* Чтобы отсортировать в порядке убывания, измените> на <. */
  17. {
  18. temp=data[steps];
  19. data[steps]=data[i];
  20. data[i]=temp;
  21. }
  22. }
  23. printf("In ascending order: ");
  24. for(i=0;i<n;++i)
  25. printf("%d ",data[i]);
  26. return 0;
  27. }
  1. Enter the number of elements to be sorted: 5
  2. 1. Enter element: 12
  3. 2. Enter element: 1
  4. 3. Enter element: 23
  5. 4. Enter element: 2
  6. 5. Enter element: 0
  7. In ascending order: 0 1 2 12 23

Note: Although this program is written in C, the selection sort algorithm can be used similarly in another programming language.

The selection sort algorithm is easy to use, but there are other sorting algorithms that perform better than selection sort. In particular, selection sort should not be used to sort a large number of items if performance matters in this program.

By article asked0question(s)

2

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html