Computer Science Module 1 Question 2(Sorting)

Contains all relevant information regarding sorting of lists, selection sort and bubble sort.

Author:Author ImageZachary Kublalsingh

Edu Level: Unit2

Date: Jul 12, 2024

⏱️Read Time:



Selection Sort

  • It takes an unsorted list
  • Assigns the first value in the list to be the smallest
  • It compares each element in the list to this "min" value
  • It swaps the min value to the smallest
  • When all elements have been compared, it swaps the value stored in min with the value stored in index 0
  • The counter is incremented.
  • This process is repeated until the list is sorted

Code

  
    #include
    int main()
    {
      int arr[10] = {20, 99, 48, 67, 19, 12, 93, 46, 18, 29} ; (can be any array)
      int i, j,min, temp;
        
      for( i = 0; i<9; i++)
      {
        min = i;
        for( j = i+1; i<10; j++)
        {
          if (arr[j] < arr[j+1])
          {
            min=j;
          }
          temp = arr[i];
          arr[i] = arr[min];
          arr[min] = temp;
        }
      }
    }
      
  

Bubble Sort

  • It takes an unsorted list
  • It compares the first element in the list to the next adjacent element
  • It swaps positions if it is in the incorrect order
  • The counter is incremented.
  • This process is repeated until the list is sorted
  • One element is in its correct position after each pass

Code

  
    #include
    int main()
    {
      int arr[10] = {20, 99, 48, 67, 19, 12, 93, 46, 18, 29} ; (can be any array)
      int i, j,temp;
        
      for( i = 0; i<10; i++)
      {
        for( j = 0; i=10-i; j++)
        {
          if (arr[j] > arr[j+1])
          {
            temp = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temp;
          }
        }
      }
    }       
  

Note - Sorting can be done in both ascending or descending order, the codes above are for ascending (smallest to largest)

Dont't forget to check out our Instagram Page!
edukatte_tt