2 Replies - 2616 Views - Last Post: 31 May 2012 - 06:37 AM Rate Topic: -----

#1 insertgenericusername  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-October 11

Pascal Bubble sort.

Posted 30 May 2012 - 03:00 PM

So basically, I need to code a bubble sort using pascal. I found code examples on a few websites, and I'm pretty sure I have copied them correctly: Sadly, when I print my array I nothing is swapped and everything is in the same order.
The procedure that does not work is refered to as Sort.

program BubbleSort;
uses SysUtils;

function ReadDouble(prompt: string):Double;
var
	line: string;
begin
	Write(prompt);
	ReadLn(line);
	while not TryStrToFloat(line, result) do
	begin
		WriteLn('Please enter a number.');
		Write(prompt);
		ReadLn(line);
	end;
end;
procedure FillData(var data: array of double);
var
	i : integer;
begin
	for i :=low(data) to high(data) do
	begin
		data[i] := ReadDouble('Please enter number ' + IntToStr(i+1) + ': ');
	end;
end;



procedure Sort(var data: array of double);
var
	i , j : integer;
	temp : double;
begin
	for i:= high(data) to low(data) do
	begin
		for j := low(data) to i-1 do
		begin
			if data[j] > data[j+1] then
			begin
			temp := data[J+1];
			data[J+1] := data[j];
			data[j] := temp;
			end;
		end;
	end;
end;

procedure PrintData(var data: array of double);
var
	i : integer;
begin
	for i := low(data) to high(data) do
	begin
		Writeln(data[i]:4:2);
	end;
end;

procedure main();
var
	data: array [0..9] of double;
begin
	FillData(data);
	Sort(data);
	PrintData(data);
end;

begin
	Main();
end.


Compiler:
Attached Image

Websites used:

http://pascal-progra...les/sorting.php

http://www.algolist....cal/Bubble_sort

Thanks in advance for any help.

This post has been edited by insertgenericusername: 30 May 2012 - 03:11 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Pascal Bubble sort.

#2 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5932
  • View blog
  • Posts: 12,855
  • Joined: 16-October 07

Re: Pascal Bubble sort.

Posted 31 May 2012 - 04:24 AM

It's not really a bubble sort, which makes me sad. The second example is simply wrong. Pascal needs downto to go backwards:
for i:= high(data) downto low(data) do



That should fix it.

As a test, try:
procedure PrintData(var data: array of double);
var
	i : integer;
begin
	for i := high(data) to low(data) do
	begin
		Writeln(data[i]:4:2);
	end;
end;



Then:
procedure PrintData(var data: array of double);
var
	i : integer;
begin
	for i := high(data) downto low(data) do
	begin
		Writeln(data[i]:4:2);
	end;
end;


Was This Post Helpful? 1
  • +
  • -

#3 insertgenericusername  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 04-October 11

Re: Pascal Bubble sort.

Posted 31 May 2012 - 06:37 AM

Thanks a heap! Works fine!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1