Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

java code for bubble sort

  1. User

    java code for bubble sort

  2. Assistant

    Below is an example of Java code for performing the Bubble Sort algorithm on an integer array:

    public class BubbleSort {
    
        public static void main(String[] args) {
            int[] array = {64, 34, 25, 12, 22, 11, 90};
            System.out.println("Unsorted array:");
            printArray(array);
    
            bubbleSort(array);
            System.out.println("Sorted array:");
            printArray(array);
        }
    
        public static void bubbleSort(int[] array) {
            int n = array.length;
            for (int i = 0; i < n - 1; i++) {
                for (int j = 0; j < n - i - 1; j++) {
                    if (array[j] > array[j + 1]) {
                        // Swap the elements
                        int temp = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = temp;
                    }
                }
            }
        }
    
        public static void printArray(int[] array) {
            for (int value : array) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
    

    This code defines a main method, a bubbleSort method for sorting the array, and a printArray method for printing the array. You can run the main method to see the unsorted and sorted arrays.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.