create a script that arranges array in ascending order without using sort in matlab

To sort an array in ascending order without using the built-in sort function in MATLAB, you can implement a simple sorting algorithm like bubble sort or insertion sort. Here's an example using bubble sort:

main.m
function sortedArray = bubbleSort(array)
    n = length(array);
    
    for i = 1:n-1
        % Traverse the array from 1 to n-i
        % Swap adjacent elements if they are in wrong order
        for j = 1:n-i
            if array(j) > array(j+1)
                temp = array(j);
                array(j) = array(j+1);
                array(j+1) = temp;
            end
        end
    end
    
    sortedArray = array;
end
426 chars
18 lines

You can call this function by passing your array as an argument, and it will return the sorted array:

main.m
array = [7, 2, 5, 1, 9];
sortedArray = bubbleSort(array);

disp(sortedArray);  % Output: [1, 2, 5, 7, 9]
105 chars
5 lines

This implementation is based on the bubble sort algorithm, which repeatedly swaps adjacent elements if they are in the wrong order. Time complexity of bubble sort is O(n^2), so for big arrays, it might not be the most efficient method.

related categories

gistlibby LogSnag