473,606 Members | 2,218 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Selection Sort

Ganon11
3,652 Recognized Expert Specialist
Earlier, mmccarthy was kind enough to post a short article explaining the Bubble Sort. As she said, this is a relatively slow sorting algorithm. Here, I will attempt to present a slightly faster algorithm called Selection Sort.

Imagine you have a list of numbers in random order. You want to sort these numbers in increasing order - that is, every element is smaller than or equal to the next element. It follows that the first element holds the smallest value, the second element holds the second smallest value, and so on.

So, to determine the first element's contents, we must find the smallest value in the rest of the list. Once we do that, we can swap this smallest value with the first element. Now the first element is finished being sorted, and we can continue with the rest of the list.

This basic process can be repeated, treating the second element of the original array as the first element in a smaller array.

To help visualize, suppose we have an array with 5 elements like this:

Index: 0 1 2 3 4
Array: 5 8 2 3 1

To determine the first element in our sorted array, we must find the smallest element in the rest of the array. This is Array[4], or 1. So we switch these values to obtain the 'new' array:

Index: 0 1 2 3 4
Array: 1 8 2 3 5

Now we consider the sub-array from 1 to 4. To determine the 'first element' of this array, we find the smallest element in the range 1-4. This happens at Array[2], or 2. So we switch these values:

Index: 0 1 2 3 4
Array: 1 2 8 3 5

Continuing in this same way, we would then switch Array[3] with Array[2], and then Array[4] with Array[3] to obtain the final, sorted array:

Index: 0 1 2 3 4
Array: 1 2 3 5 8

Now, how to put this into code? I usually implement this algorithm using 2 nested for...loops. The first loop goes from 0 to n-1, where n is the size of the array. This is because we must consider individually each sub-array Array(i) such that Array(i) contains values at Array[i], Array[i+1], Array[i+2]...Array[n-1] to sort. When we check each sub-array, we must have a variable to hold the position of the smallest value we have found. This will change throughout the execution of the second loop. Before we begin checking any values, we assume that the smallest value is Array[i], so smallest contains i. This makes sense - we have checked only one value, so that value must be the smallest.

The second for loop will go from i (the index of the first loop) to n-1. This loop is finding the smallest element in the sub-array Array(i). Let us say that this loop uses j as its index. This means that we must check if Array[j] is less than Array[smallest] - if it is, we have found a new smallest value, and must assign j to smallest.

Once this second loop has finished executing, we know that smallest contains the index of the smallest value in Array(i). We then swap the values at Array[i] (the first element in Array(i)) and Array[smallest] (the smallest element in Array(i)). Now we have finished with this execution of the first for loop.

In pseudocode, the above becomes:

Expand|Select|Wrap|Line Numbers
  1. void SELECTIONSORT(int array[], int n) { // n is the size of the array
  2.    FOR (i loops from 0 to n-1)
  3.       int smallest = i
  4.       FOR (j loops from i to n-1)
  5.          IF (array[j] is smaller than array[smallest])
  6.             smallest = j
  7.       SWAP(array, i, smallest)
  8. }
To make the code shorter, I used a function SWAP that will swap the elements in array. This is a short function that looks something like this:

Expand|Select|Wrap|Line Numbers
  1. void SWAP(int array[], int from, int to) {
  2.    int temp = array[from];
  3.    array[from] = array[to];
  4.    array[to] = temp;
  5. }
May 7 '07 #1
0 8512

Sign in to post your reply or Sign up for a free account.

Similar topics

5
2439
by: Jim Cobban | last post by:
I am trying to create a web page in which the contents of one selection list depends upon which element in another selection list is chosen, but where the information to populate the first selection list comves from an SQL database on the web server. There are a couple of these situations in my application but, for example, the first list might be a list of counties, and the second list a list of states/provinces. Obviously the names of...
5
4566
by: srampally | last post by:
I need the capabilty to hide/show a selection list, just the way its done at http://www.lufthansa.com (place the cursor over "Group Companies"). However, I am looking for a javascript that is much simpler. Here is what I have until now. Problems with my code: 1. The selection list becomes invisible when I try to select an option (in Firefox). 2. The selection list stays visible when I just place the cursor over selection list and move...
13
2686
by: ANSHUL | last post by:
PLEASE PROVIDE ME D SOLUTION CODE FOR DIS PROBLEM. SELECTION SORT IS BASED ON D FOLLOWING IDEA: SELECTING D LARGEST ARRAY ELEMENT AND SWAPPING IT WITH THE LAST ARRAY ELEMENT LEAVES AN UNSORTED LIST WHOSE SIZE IS I LESS THAN THE SIZE OF ORIGINAL LIST. IF V REPEAT THIS STEP AGAIN ON D UNSORTED LIST V WILL HAVE AN ORDERED LIST OF SIZE 2 AND UNORDERED LIST SIZE OF N-2(N IS D TOTAL NUMBER OF ARRAY ELEMENTS).WHEN WE REPEAT THIS UNTIL THE SIZE...
4
5863
by: shaveta | last post by:
pls help me to write a program in c that reads n elements of type float, stores them in a linked list ,sort it in the descending order using selection sort methods, and finally output the sorted linear linked list
1
4158
by: gemacjr1201 | last post by:
I need hints for an algorithm using string compare in a selection sort. I will be sorting lastnames and first namesalphbetically. if the selection sort encounters the same last name it then goes to first name and alphabetizes the list. Smith, John Smith, Juan THANKS IN ADVANCE!!
1
3640
by: ShaveDave27 | last post by:
Hi, I've created a Person Class with a comparable interface. And i've created an ArrayList People with varaibles from the person class in - First_name, Surname, Month(Birthday), Day(Birthday). Now i need to use selection sort to sort my arraylist into birthday order. In the Person Class i have a method which gives each person a different number for every possible birthday there is. I have created a selction sort but dont know how to call...
1
3399
by: neyugncul | last post by:
Okay, I have this homework assignment which is to sort a 2D array of characters using selection sort. I've written the selection sort but I can't seem to get it working. (it's not sorting!) Please tell me what I'm doing wrong, thanks. void selectionSort(char array, int rows) { const int size = 17;
4
2558
by: sialater | last post by:
Hello, I realise there are a lot of topics related to this problem but many of what I have found has run cold or unresolved. What I have is an addressbook clone where there are groups which have members. I have this formatted in a way where the groups are in a drop down box. Once a group is selected, the two selection boxes below are refreshed with those who are members or non members of the selected group. The user has the ability to...
1
13296
by: HarishAdea | last post by:
Hi, I am trying to run the JAVA pgm, but it is giving error as "selection does not contain a main type". The filename is "ScoreLeadSummary.java" when i try to run it or debug,it gives the pop up as "selection does not contain a main type" Please help me out in resolving the above issue to run the .java file. I am facing same issue with other .java files inside the project The code is as shown below: package...
0
8015
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7951
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8439
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8430
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8094
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8305
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
3977
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2448
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1553
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.