bubble sort in matlab

Here is an implementation of bubble sort in MATLAB:

main.m
function sortedArr = bubbleSort(arr)
% BUBBLESORT Sort an input array using BubbleSort algorithm

n = length(arr);
for i = 1:n-1
    for j = 1:n-i
        if arr(j) > arr(j+1)
            % swap
            temp = arr(j);
            arr(j) = arr(j+1);
            arr(j+1) = temp;
        end
    end
end
sortedArr = arr;
end
327 chars
17 lines

The function takes an input array arr and applies the bubble sort algorithm to sort its elements in ascending order. It returns the sorted array sortedArr.

Here's an example usage:

main.m
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5];
sortedArr = bubbleSort(arr);
disp(sortedArr); % [1, 1, 2, 3, 4, 5, 5, 6, 9]
111 chars
4 lines

In this example, the input array is [3, 1, 4, 1, 5, 9, 2, 6, 5] and we've used the bubbleSort function to sort it.

Note that bubble sort is not usually efficient for large arrays or data sets, as it has a time complexity of O(n^2). Other sorting algorithms like quicksort or mergesort may be better options for larger data sets.

related categories

gistlibby LogSnag