Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which happens to be next to it, in the previous array-position checked). If larger, it leaves the element in place and moves to the next. If smaller, it finds the correct position within the sorted list, shifts all the larger values up to make a space, and inserts into that correct position.
The resulting array after k iterations has the property where the first k + 1 entries are sorted ("+1" because the first entry is skipped). In each iteration the first remaining entry of the input is removed, and inserted into the result at the correct position, thus extending the result:
Write a program that uses the Insertion sort algorithm to sort a list of numbers that are read in from a file (random.txt) and then writes the sorted numbers to a second file.
Heres what I have so far
x = load('random.txt');
lengthofarray = length(x);
fileID = fopen('random.txt');
fprintf(fileID,x);
fclose(fileID);
for i = 1:lengthofarray
for j = 1:(lengthofarray – i)
if x(j)> x(j+1)
temp=x(j);
x(j)=x(j+1);
x(j+1)=temp;
end
end
end
Best Answer