Bubble sort

#Bubble Sort
nums = [9, 4, 5, 1, 3, 7, 6]
for i in range(len(nums)):
    for j in range(1, len(nums)):
        if nums[j] < nums[j - 1]:
            nums[j], nums[j - 1] = nums[j - 1], nums[j]

4.75
8
Phoenix Logan 186125 points

                                    class Sort 
{
    static void bubbleSort(int arr[], int n)
    {                                       
        if (n == 1)                     //passes are done
        {
            return;
        }

        for (int i=0; i&lt;n-1; i++)       //iteration through unsorted elements
        {
            if (arr[i] &gt; arr[i+1])      //check if the elements are in order
            {                           //if not, swap them
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
            }
        }
            
        bubbleSort(arr, n-1);           //one pass done, proceed to the next
    }

    void display(int arr[])                 //display the array
    {  
        for (int i=0; i&lt;arr.length; ++i) 
        {
            System.out.print(arr[i]+&quot; &quot;);
        } 
    } 
     
    public static void main(String[] args)
    {
        Sort ob = new Sort();
        int arr[] = {6, 4, 5, 12, 2, 11, 9};    
        bubbleSort(arr, arr.length);
        ob.display(arr);
    }
}

4.75 (8 Votes)
0
3.67
6
Phoenix Logan 186125 points

                                    import static java.lang.Integer.parseInt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.StringTokenizer;

public class Day20_Sorting {

	static int MB = 1 &lt;&lt; 20;
	static BufferedReader BR = new BufferedReader( new InputStreamReader(System.in, StandardCharsets.US_ASCII), 20 * MB);
	
	static StringTokenizer st;
	static String lastLine;
	
	static void newLine() throws IOException {
		lastLine = BR.readLine();
		st = new StringTokenizer(lastLine);
	}
	
	public static void main(String[] args) throws IOException {
		newLine();
		int N = parseInt(st.nextToken());
		
		newLine();
		int[] A = new int[N];
		for (int i = 0; i &lt; N; i++) {
			A[i] = parseInt(st.nextToken());
		}

		int numberOfSwapps = bubbleSort(N, A);
		int firstElement = A[0];
		int lastElement = A[N-1];
		print(numberOfSwapps, firstElement, lastElement);
	}

	private static void print(int numberOfSwapps, int firstElement, int lastElement) {
		StringBuilder sb = new StringBuilder();
		
		sb.append(&quot;Array is sorted in &quot;).append(numberOfSwapps).append(&quot; swaps.\n&quot;);
		sb.append(&quot;First Element: &quot;).append(firstElement).append('\n');
		sb.append(&quot;Last Element: &quot;).append(lastElement).append('\n');
		
		System.out.print(sb);
	}

	private static int bubbleSort(int N, int[] A) {
		int cnt = 0;
		
		for (int i = 0; i &lt; N; i++) {
		    // Track number of elements swapped during a single array traversal
		    int numberOfSwaps = 0;
		    
		    for (int j = 0; j &lt; N - 1; j++) {
		        // Swap adjacent elements if they are in decreasing order
		        if (A[j] &gt; A[j + 1]) {
		            swap(A, j , j + 1);
		            numberOfSwaps++;
		        }
		    }
		    cnt += numberOfSwaps;
		    
		    // If no elements were swapped during a traversal, array is sorted
		    if (numberOfSwaps == 0) {
		        break;
		    }
		}
		
		return cnt;
	}

	private static void swap(int[] a, int i, int j) {
		int tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
	}

}

3.67 (6 Votes)
0
4.1
10
Krish 100200 points

                                    /*bubble sort;timecomplexity=O(n){best case}
               time complexity=O(n^2){worst case}
               space complexity=O(n);auxiliary space commplexity=O(1)
*/
#include &lt;iostream&gt;

using namespace std;
void swap(int*,int*);
void bubble_sort(int arr[],int n)
{
    for(int i=0;i&lt;n-1;i++)
    {
        for(int j=0;j&lt;n-1-i;j++)
        {
            if(arr[j]&gt;arr[j+1])
            {
                swap(&amp;arr[j],&amp;arr[j+1]);
            }
        }
    }
}
void display(int arr[],int n)
{
    for(int i=0;i&lt;n;i++)
    {
        cout&lt;&lt;arr[i]&lt;&lt;&quot; &quot;;
    }
    cout&lt;&lt;endl;
}

int main()
{
    int n;
    cout&lt;&lt;&quot;enter the size of the array:&quot;&lt;&lt;endl;
    cin&gt;&gt;n;
    int array_of_numbers[n];
    cout&lt;&lt;&quot;enter the elements of the array&quot;&lt;&lt;endl;
    for(int i=0;i&lt;n;i++)
    {
        cin&gt;&gt;array_of_numbers[i];
    }
    cout&lt;&lt;&quot;array as it was entered:&quot;&lt;&lt;endl;
    display(array_of_numbers,n);
    bubble_sort(array_of_numbers,n);
    cout&lt;&lt;&quot;array after bubble sort:&quot;&lt;&lt;endl;
    display(array_of_numbers,n);
    return 0;
}
void swap(int *a,int *b)
{
    int temp=*a;
    *a=*b;
    *b=temp;
}

4.1 (10 Votes)
0
3.33
3
Awgiedawgie 440220 points

                                    using System; 
public class Bubble_Sort  
{  
   public static void Main(string[] args)
         { 
            int[] a = { 3, 0, 2, 5, -1, 4, 1 }; 
			int t; 
			Console.WriteLine(&quot;Original array :&quot;);
            foreach (int aa in a)                       
            Console.Write(aa + &quot; &quot;);                     
            for (int p = 0; p &lt;= a.Length - 2; p++)
            {
                for (int i = 0; i &lt;= a.Length - 2; i++)
                {
                    if (a[i] &gt; a[i + 1])
                    {
                        t = a[i + 1];
                        a[i + 1] = a[i];
                        a[i] = t;
                    }
                } 
            }
            Console.WriteLine(&quot;\n&quot;+&quot;Sorted array :&quot;);
            foreach (int aa in a)                       
            Console.Write(aa + &quot; &quot;);
			Console.Write(&quot;\n&quot;); 
            
        }
}

3.33 (3 Votes)
0
0
0
Awgiedawgie 440220 points

                                    // I Love Java
import java.io.*;
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.toList;

public class Bubble_Sort_P {
    public static void main(String[] args) throws IOException {
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

        List&lt;Integer&gt; arr = Stream.of(buffer.readLine().replaceAll(&quot;\\s+$&quot;, &quot; &quot;).split(&quot; &quot;)).map(Integer::parseInt)
                .collect(toList());

        calculate(arr);

        System.out.println(arr);
    }

    public static void calculate(List&lt;Integer&gt; arr) {
        for (int i = 0; i &lt;= arr.size() - 2; i++) {
            if (arr.get(i) &gt; arr.get(i + 1)) {
                int tem = arr.get(i);
                arr.set(i, arr.get(i + 1));
                arr.set(i + 1, tem);
                calculate(arr);
            }
        }
    }
}

0
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source