• Admiral “Amazing Grace” Hopper

Exploring the Intricacies of NP-Completeness in Computer Science

Understanding p vs np problems in computer science: a primer for beginners, understanding key theoretical frameworks in computer science: a beginner’s guide.

Learn Computer Science with Python

Learn Computer Science with Python

CS is a journey, not a destination

  • Foundations

Understanding Algorithms: The Key to Problem-Solving Mastery

algorithmic problem solving computer science

The world of computer science is a fascinating realm, where intricate concepts and technologies continuously shape the way we interact with machines. Among the vast array of ideas and principles, few are as fundamental and essential as algorithms. These powerful tools serve as the building blocks of computation, enabling computers to solve problems, make decisions, and process vast amounts of data efficiently.

An algorithm can be thought of as a step-by-step procedure or a set of instructions designed to solve a specific problem or accomplish a particular task. It represents a systematic approach to finding solutions and provides a structured way to tackle complex computational challenges. Algorithms are at the heart of various applications, from simple calculations to sophisticated machine learning models and complex data analysis.

Understanding algorithms and their inner workings is crucial for anyone interested in computer science. They serve as the backbone of software development, powering the creation of innovative applications across numerous domains. By comprehending the concept of algorithms, aspiring computer science enthusiasts gain a powerful toolset to approach problem-solving and gain insight into the efficiency and performance of different computational methods.

In this article, we aim to provide a clear and accessible introduction to algorithms, focusing on their importance in problem-solving and exploring common types such as searching, sorting, and recursion. By delving into these topics, readers will gain a solid foundation in algorithmic thinking and discover the underlying principles that drive the functioning of modern computing systems. Whether you’re a beginner in the world of computer science or seeking to deepen your understanding, this article will equip you with the knowledge to navigate the fascinating world of algorithms.

What are Algorithms?

At its core, an algorithm is a systematic, step-by-step procedure or set of rules designed to solve a problem or perform a specific task. It provides clear instructions that, when followed meticulously, lead to the desired outcome.

Consider an algorithm to be akin to a recipe for your favorite dish. When you decide to cook, the recipe is your go-to guide. It lists out the ingredients you need, their exact quantities, and a detailed, step-by-step explanation of the process, from how to prepare the ingredients to how to mix them, and finally, the cooking process. It even provides an order for adding the ingredients and specific times for cooking to ensure the dish turns out perfect.

In the same vein, an algorithm, within the realm of computer science, provides an explicit series of instructions to accomplish a goal. This could be a simple goal like sorting a list of numbers in ascending order, a more complex task such as searching for a specific data point in a massive dataset, or even a highly complicated task like determining the shortest path between two points on a map (think Google Maps). No matter the complexity of the problem at hand, there’s always an algorithm working tirelessly behind the scenes to solve it.

Furthermore, algorithms aren’t limited to specific programming languages. They are universal and can be implemented in any language. This is why understanding the fundamental concept of algorithms can empower you to solve problems across various programming languages.

The Importance of Algorithms

Algorithms are indisputably the backbone of all computational operations. They’re a fundamental part of the digital world that we interact with daily. When you search for something on the web, an algorithm is tirelessly working behind the scenes to sift through millions, possibly billions, of web pages to bring you the most relevant results. When you use a GPS to find the fastest route to a location, an algorithm is computing all possible paths, factoring in variables like traffic and road conditions, to provide you the optimal route.

Consider the world of social media, where algorithms curate personalized feeds based on our previous interactions, or in streaming platforms where they recommend shows and movies based on our viewing habits. Every click, every like, every search, and every interaction is processed by algorithms to serve you a seamless digital experience.

In the realm of computer science and beyond, everything revolves around problem-solving, and algorithms are our most reliable problem-solving tools. They provide a structured approach to problem-solving, breaking down complex problems into manageable steps and ensuring that every eventuality is accounted for.

Moreover, an algorithm’s efficiency is not just a matter of preference but a necessity. Given that computers have finite resources — time, memory, and computational power — the algorithms we use need to be optimized to make the best possible use of these resources. Efficient algorithms are the ones that can perform tasks more quickly, using less memory, and provide solutions to complex problems that might be infeasible with less efficient alternatives.

In the context of massive datasets (the likes of which are common in our data-driven world), the difference between a poorly designed algorithm and an efficient one could be the difference between a solution that takes years to compute and one that takes mere seconds. Therefore, understanding, designing, and implementing efficient algorithms is a critical skill for any computer scientist or software engineer.

Hence, as a computer science beginner, you are starting a journey where algorithms will be your best allies — universal keys capable of unlocking solutions to a myriad of problems, big or small.

Common Types of Algorithms: Searching and Sorting

Two of the most ubiquitous types of algorithms that beginners often encounter are searching and sorting algorithms.

Searching algorithms are designed to retrieve specific information from a data structure, like an array or a database. A simple example is the linear search, which works by checking each element in the array until it finds the one it’s looking for. Although easy to understand, this method isn’t efficient for large datasets, which is where more complex algorithms like binary search come in.

Binary search, on the other hand, is like looking up a word in the dictionary. Instead of checking each word from beginning to end, you open the dictionary in the middle and see if the word you’re looking for should be on the left or right side, thereby reducing the search space by half with each step.

Sorting algorithms, meanwhile, are designed to arrange elements in a particular order. A simple sorting algorithm is bubble sort, which works by repeatedly swapping adjacent elements if they’re in the wrong order. Again, while straightforward, it’s not efficient for larger datasets. More advanced sorting algorithms, such as quicksort or mergesort, have been designed to sort large data collections more efficiently.

Diving Deeper: Graph and Dynamic Programming Algorithms

Building upon our understanding of searching and sorting algorithms, let’s delve into two other families of algorithms often encountered in computer science: graph algorithms and dynamic programming algorithms.

A graph is a mathematical structure that models the relationship between pairs of objects. Graphs consist of vertices (or nodes) and edges (where each edge connects a pair of vertices). Graphs are commonly used to represent real-world systems such as social networks, web pages, biological networks, and more.

Graph algorithms are designed to solve problems centered around these structures. Some common graph algorithms include:

Dynamic programming is a powerful method used in optimization problems, where the main problem is broken down into simpler, overlapping subproblems. The solutions to these subproblems are stored and reused to build up the solution to the main problem, saving computational effort.

Here are two common dynamic programming problems:

Understanding these algorithm families — searching, sorting, graph, and dynamic programming algorithms — not only equips you with powerful tools to solve a variety of complex problems but also serves as a springboard to dive deeper into the rich ocean of algorithms and computer science.

Recursion: A Powerful Technique

While searching and sorting represent specific problem domains, recursion is a broad technique used in a wide range of algorithms. Recursion involves breaking down a problem into smaller, more manageable parts, and a function calling itself to solve these smaller parts.

To visualize recursion, consider the task of calculating factorial of a number. The factorial of a number n (denoted as n! ) is the product of all positive integers less than or equal to n . For instance, the factorial of 5 ( 5! ) is 5 x 4 x 3 x 2 x 1 = 120 . A recursive algorithm for finding factorial of n would involve multiplying n by the factorial of n-1 . The function keeps calling itself with a smaller value of n each time until it reaches a point where n is equal to 1, at which point it starts returning values back up the chain.

Algorithms are truly the heart of computer science, transforming raw data into valuable information and insight. Understanding their functionality and purpose is key to progressing in your computer science journey. As you continue your exploration, remember that each algorithm you encounter, no matter how complex it may seem, is simply a step-by-step procedure to solve a problem.

We’ve just scratched the surface of the fascinating world of algorithms. With time, patience, and practice, you will learn to create your own algorithms and start solving problems with confidence and efficiency.

Related Articles

algorithmic problem solving computer science

Three Elegant Algorithms Every Computer Science Beginner Should Know

Smart. Open. Grounded. Inventive. Read our Ideas Made to Matter.

Which program is right for you?

MIT Sloan Campus life

Through intellectual rigor and experiential learning, this full-time, two-year MBA program develops leaders who make a difference in the world.

A rigorous, hands-on program that prepares adaptive problem solvers for premier finance careers.

A 12-month program focused on applying the tools of modern data science, optimization and machine learning to solve real-world business problems.

Earn your MBA and SM in engineering with this transformative two-year program.

Combine an international MBA with a deep dive into management science. A special opportunity for partner and affiliate schools only.

A doctoral program that produces outstanding scholars who are leading in their fields of research.

Bring a business perspective to your technical and quantitative expertise with a bachelor’s degree in management, business analytics, or finance.

A joint program for mid-career professionals that integrates engineering and systems thinking. Earn your master’s degree in engineering and management.

An interdisciplinary program that combines engineering, management, and design, leading to a master’s degree in engineering and management.

Executive Programs

A full-time MBA program for mid-career leaders eager to dedicate one year of discovery for a lifetime of impact.

This 20-month MBA program equips experienced executives to enhance their impact on their organizations and the world.

Non-degree programs for senior executives and high-potential managers.

A non-degree, customizable program for mid-career professionals.

How AI helps acquired businesses grow

Leading the AI-driven organization

New AI insights from MIT Sloan Management Review

Credit: Alejandro Giraldo

Ideas Made to Matter

How to use algorithms to solve everyday problems

Kara Baskin

May 8, 2017

How can I navigate the grocery store quickly? Why doesn’t anyone like my Facebook status? How can I alphabetize my bookshelves in a hurry? Apple data visualizer and MIT System Design and Management graduate Ali Almossawi solves these common dilemmas and more in his new book, “ Bad Choices: How Algorithms Can Help You Think Smarter and Live Happier ,” a quirky, illustrated guide to algorithmic thinking. 

For the uninitiated: What is an algorithm? And how can algorithms help us to think smarter?

An algorithm is a process with unambiguous steps that has a beginning and an end, and does something useful.

Algorithmic thinking is taking a step back and asking, “If it’s the case that algorithms are so useful in computing to achieve predictability, might they also be useful in everyday life, when it comes to, say, deciding between alternative ways of solving a problem or completing a task?” In all cases, we optimize for efficiency: We care about time or space.

Note the mention of “deciding between.” Computer scientists do that all the time, and I was convinced that the tools they use to evaluate competing algorithms would be of interest to a broad audience.

Why did you write this book, and who can benefit from it?

All the books I came across that tried to introduce computer science involved coding. My approach to making algorithms compelling was focusing on comparisons. I take algorithms and put them in a scene from everyday life, such as matching socks from a pile, putting books on a shelf, remembering things, driving from one point to another, or cutting an onion. These activities can be mapped to one or more fundamental algorithms, which form the basis for the field of computing and have far-reaching applications and uses.

I wrote the book with two audiences in mind. One, anyone, be it a learner or an educator, who is interested in computer science and wants an engaging and lighthearted, but not a dumbed-down, introduction to the field. Two, anyone who is already familiar with the field and wants to experience a way of explaining some of the fundamental concepts in computer science differently than how they’re taught.

I’m going to the grocery store and only have 15 minutes. What do I do?

Do you know what the grocery store looks like ahead of time? If you know what it looks like, it determines your list. How do you prioritize things on your list? Order the items in a way that allows you to avoid walking down the same aisles twice.

For me, the intriguing thing is that the grocery store is a scene from everyday life that I can use as a launch pad to talk about various related topics, like priority queues and graphs and hashing. For instance, what is the most efficient way for a machine to store a prioritized list, and what happens when the equivalent of you scratching an item from a list happens in the machine’s list? How is a store analogous to a graph (an abstraction in computer science and mathematics that defines how things are connected), and how is navigating the aisles in a store analogous to traversing a graph?

Nobody follows me on Instagram. How do I get more followers?

The concept of links and networks, which I cover in Chapter 6, is relevant here. It’s much easier to get to people whom you might be interested in and who might be interested in you if you can start within the ball of links that connects those people, rather than starting at a random spot.

You mention Instagram: There, the hashtag is one way to enter that ball of links. Tag your photos, engage with users who tag their photos with the same hashtags, and you should be on your way to stardom.

What are the secret ingredients of a successful Facebook post?

I’ve posted things on social media that have died a sad death and then posted the same thing at a later date that somehow did great. Again, if we think of it in terms that are relevant to algorithms, we’d say that the challenge with making something go viral is really getting that first spark. And to get that first spark, a person who is connected to the largest number of people who are likely to engage with that post, needs to share it.

With [my first book], “Bad Arguments,” I spent a month pouring close to $5,000 into advertising for that project with moderate results. And then one science journalist with a large audience wrote about it, and the project took off and hasn’t stopped since.

What problems do you wish you could solve via algorithm but can’t?

When we care about efficiency, thinking in terms of algorithms is useful. There are cases when that’s not the quality we want to optimize for — for instance, learning or love. I walk for several miles every day, all throughout the city, as I find it relaxing. I’ve never asked myself, “What’s the most efficient way I can traverse the streets of San Francisco?” It’s not relevant to my objective.

Algorithms are a great way of thinking about efficiency, but the question has to be, “What approach can you optimize for that objective?” That’s what worries me about self-help: Books give you a silver bullet for doing everything “right” but leave out all the nuances that make us different. What works for you might not work for me.

Which companies use algorithms well?

When you read that the overwhelming majority of the shows that users of, say, Netflix, watch are due to Netflix’s recommendation engine, you know they’re doing something right.

Related Articles

A stack of jeans with network/AI imagery overlayed on top

Have a language expert improve your writing

Check your paper for plagiarism in 10 minutes, generate your apa citations for free.

  • Knowledge Base
  • Using AI tools
  • What Is an Algorithm? | Definition & Examples

What Is an Algorithm? | Definition & Examples

Published on August 9, 2023 by Kassiani Nikolopoulou . Revised on August 29, 2023.

An algorithm is a set of steps for accomplishing a task or solving a problem. Typically, algorithms are executed by computers, but we also rely on algorithms in our daily lives. Each time we follow a particular step-by-step process, like making coffee in the morning or tying our shoelaces, we are in fact following an algorithm.

In the context of computer science , an algorithm is a mathematical process for solving a problem using a finite number of steps. Algorithms are a key component of any computer program and are the driving force behind various systems and applications, such as navigation systems, search engines, and music streaming services.

Instantly correct all language mistakes in your text

Upload your document to correct all your mistakes in minutes

upload-your-document-ai-proofreader

Table of contents

What is an algorithm, how do algorithms work, examples of algorithms, other interesting articles, frequently asked questions about algorithms.

An algorithm is a sequence of instructions that a computer must perform to solve a well-defined problem. It essentially defines what the computer needs to do and how to do it. Algorithms can instruct a computer how to perform a calculation, process data, or make a decision.

The best way to understand an algorithm is to think of it as a recipe that guides you through a series of well-defined actions to achieve a specific goal. Just like a recipe produces a replicable result, algorithms ensure consistent and reliable outcomes for a wide range of tasks in the digital realm.

And just like there are numerous ways to make, for example, chocolate chip cookies by following different steps or using slightly different ingredients, different algorithms can be designed to solve the same problem, with each taking a distinct approach but achieving the same result.

Algorithms are virtually everywhere around us. Examples include the following:

  • Search engines rely on algorithms to find and present relevant results as quickly as possible
  • Social media platforms use algorithms to prioritize the content that we see in our feeds, taking into account factors like our past behavior, the popularity of posts, and relevance.
  • With the help of algorithms, navigation apps determine the most efficient route for us to reach our destination.
  • It must be correct . In other words, it should take a given problem and provide the right answer or result, even if it stops working due to an error.
  • It must consist of clear, practical steps that can be completed in a limited time, whether by a person or the machine that must execute the algorithm. For example, the instructions in a cookie recipe might be considered sufficiently concrete for a human cook, but they would not be specific enough for programming an automated cookie-making machine.
  • There should be no confusion about which step comes next , even if choices must be made (e.g., when using “if” statements).
  • It must have a set number of steps (not an infinite number) that can be managed using loops (statements describing repeated actions or iterations).
  • It must eventually reach an endpoint and not get stuck in a never-ending loop.

Check for common mistakes

Use the best grammar checker available to check for common mistakes in your text.

Fix mistakes for free

Algorithms use a set of initial data or input , process it through a series of logical steps or rules, and produce the output (i.e., the outcome, decision, or result).

Algorithm boxes

If you want to make chocolate chip cookies, for instance, the input would be the ingredients and quantities, the process would be the recipe you choose to follow, and the output would be the cookies.

Algorithms are eventually expressed in a programming language that a computer can process. However, when an algorithm is being created, it will be people, not a computer, who will need to understand it. For this reason, as a first step, algorithms are written as plain instructions.

  • Input: the input data is a single-digit number (e.g., 5).
  • Transformation/processing: the algorithm takes the input (number 5) and performs the specific operation (i.e., multiplies the number by itself).
  • Output: the result of the calculation is the square of the input number, which, in this case, would be 25 (since 5 * 5 = 25).

We could express this as an algorithm in the following way:

Algorithm: Calculate the square of a number

  • Input the number (N) whose square you want to find.
  • Multiply the number (N) by itself.
  • Store the result of the multiplication in a variable (result).
  • Output the value of the variable (result), which represents the square of the input number.

It is important to keep in mind that an algorithm is not the same as a program or code. It is the logic or plan for solving a problem represented as a simple step-by-step description. Code is the implementation of the algorithm in a specific programming language (like C++ or Python), while a program is an implementation of code that instructs a computer on how to execute an algorithm and perform a task.

Instead of telling a computer exactly what to do, some algorithms allow computers to learn on their own and improve their performance on a specific task. These machine learning algorithms use data to identify patterns and make predictions or conduct data mining to uncover hidden insights in data that can inform business decisions.

Broadly speaking, there are three different types of algorithms:

  • Linear sequence algorithms follow a specific set or steps, one after the other. Just like following a recipe, each step depends on the success of the previous one.
  • For example, in the context of a cookie recipe, you would include the step “if the dough is too sticky, you might need to refrigerate it.”
  • For example, a looping algorithm could be used to handle the process of making multiple cookies from a single batch of dough. The algorithm would repeat a specific set of instructions to form and bake cookies until all the dough has been used.

Algorithms are fundamental tools for problem-solving in both the digital world and many real-life scenarios. Each time we try to solve a problem by breaking it down into smaller, manageable steps, we are in fact using algorithmic thinking.

  • Identify which clothes are clean.
  • Consider the weather forecast for the day.
  • Consider the occasion for which you are getting dressed (e.g., work or school etc.).
  • Consider personal preferences (e.g., style or which items match).

In mathematics, algorithms are standard methods for performing calculations or solving equations because they are efficient, reliable, and applicable to various situations.

Suppose you want to add the numbers 345 and 278. You would follow a set of steps (i.e., the standard algorithm for addition):

  • Write down the numbers so the digits align.
  • Start from the rightmost digits (the ones place) and add them together: 5 + 8 = 13. Write down the 3 and carry over the 1 to the next column.
  • Move to the next column (the tens place) and add the digits along with the carried-over value: 4 + 7 + 1 = 12. Write down the 2 and carry over the 1 to the next column.
  • Move to the leftmost column (the hundreds place) and add the digits along with the carried-over value: 3 + 2 + 1 = 6. Write down the 6.

The final result is 623

Algorithm calculation example

Navigation systems are another example of the use of algorithms. Such systems use algorithms to help you find the easiest and fastest route to your destination while avoiding traffic jams and roadblocks.

If you want to know more about ChatGPT, AI tools , fallacies , and research bias , make sure to check out some of our other articles with explanations and examples.

  • ChatGPT vs human editor
  • ChatGPT citations
  • Is ChatGPT trustworthy?
  • Using ChatGPT for your studies
  • Sunk cost fallacy
  • Straw man fallacy
  • Slippery slope fallacy
  • Red herring fallacy
  • Ecological fallacy
  • Logical fallacy

Research bias

  • Implicit bias
  • Framing bias
  • Cognitive bias
  • Optimism bias
  • Hawthorne effect
  • Unconscious bias

In computer science, an algorithm is a list of unambiguous instructions that specify successive steps to solve a problem or perform a task. Algorithms help computers execute tasks like playing games or sorting a list of numbers. In other words, computers use algorithms to understand what to do and give you the result you need.

Algorithms and artificial intelligence (AI) are not the same, however they are closely related.

  • Artificial intelligence is a broad term describing computer systems performing tasks usually associated with human intelligence like decision-making, pattern recognition, or learning from experience.
  • Algorithms are the instructions that AI uses to carry out these tasks, therefore we could say that algorithms are the building blocks of AI—even though AI involves more advanced capabilities beyond just following instructions.

Algorithms and computer programs are sometimes used interchangeably, but they refer to two distinct but interrelated concepts.

  • An algorithm is a step-by-step instruction for solving a problem that is precise yet general.
  • Computer programs are specific implementations of an algorithm in a specific programming language. In other words, the algorithm is the high-level description of an idea, while the program is the actual implementation of that idea.

Algorithms are valuable to us because they:

  • Form the basis of much of the technology we use in our daily lives, from mobile apps to search engines.
  • Power innovations in various industries that augment our abilities (e.g., AI assistants or medical diagnosis).
  • Help analyze large volumes of data, discover patterns and make informed decisions in a fast and efficient way, at a scale humans are simply not able to do.
  • Automate processes. By streamlining tasks, algorithms increase efficiency, reduce errors, and save valuable time.

Cite this Scribbr article

If you want to cite this source, you can copy and paste the citation or click the “Cite this Scribbr article” button to automatically add the citation to our free Citation Generator.

Nikolopoulou, K. (2023, August 29). What Is an Algorithm? | Definition & Examples. Scribbr. Retrieved April 2, 2024, from https://www.scribbr.com/ai-tools/what-is-an-algorithm/

Is this article helpful?

Kassiani Nikolopoulou

Kassiani Nikolopoulou

Other students also liked, what is deep learning | a beginner's guide, what is data mining | definition & techniques, what is machine learning | a beginner's guide.

Kassiani Nikolopoulou

Kassiani Nikolopoulou (Scribbr Team)

Thanks for reading! Hope you found this article helpful. If anything is still unclear, or if you didn’t find what you were looking for here, leave a comment and we’ll see if we can help.

Still have questions?

Unlimited academic ai-proofreading.

✔ Document error-free in 5minutes ✔ Unlimited document corrections ✔ Specialized in correcting academic texts

Problem-Solving Strategies

  • First Online: 06 August 2020

Cite this chapter

Book cover

  • Orit Hazzan   ORCID: orcid.org/0000-0002-8627-0997 4 ,
  • Noa Ragonis   ORCID: orcid.org/0000-0002-8163-0199 5 &
  • Tami Lapidot 4  

1329 Accesses

Problem-solving is generally considered as one of the most important and challenging cognitive activities in everyday as well as in any professional contexts. Specifically, it is one of the central activities performed by computer scientists as well as by computer science learners. However, it is not a uniform or linear process that can be taught as an algorithm to be followed, and the understanding of this individual process is not always clear. Computer science learners often face difficulties in performing two of the main stages of a problem-solving process: problem analysis and solution construction. Therefore, it is important that computer science educators be aware of these difficulties and acquire appropriate pedagogical tools to guide and scaffold learners in learning these skills. This chapter is dedicated to such pedagogical tools. It presents several problem-solving strategies to address in the MTCS course together with appropriate activities that mediate them to the prospective computer science teachers by enabling them to experience the different strategies.

This is a preview of subscription content, log in via an institution to check access.

Access this chapter

  • Available as PDF
  • Read on any device
  • Instant download
  • Own it forever
  • Available as EPUB and PDF
  • Compact, lightweight edition
  • Dispatched in 3 to 5 business days
  • Free shipping worldwide - see info
  • Durable hardcover edition

Tax calculation will be finalised at checkout

Purchases are for personal use only

Institutional subscriptions

An algorithmic problem is defined by what is given – the initial conditions of the problem and its goals – the desired state, what should be accomplished. An algorithm problem can be solved with a series of actions formulated formally either by pseudo-code or a programming language. See Sect. 12.4.1 .

In advanced computer science classes, it is relevant to mention that in computer science, in addition to the development of problem-solving strategies, special emphasis is placed also on non-solvable problems (see Sect. 12.4.3 ).

Role of Variables in Python: http://www.cs.joensuu.fi/~saja/var_roles/stud_vers/stud_Python_eng.html

Roles of Variables with examples in Scratch: https://www.sisd.net/cms/lib/TX01001452/Centricity/domain/433/cse/1.1.5%20RolesOfVariables_UsedActivity1.2.4.pptx

The Roles of Variables home page ( http://saja.kapsi.fi/var_roles/ ) is a rich resource and contains different kinds of educational resources.

See http://www.cs.joensuu.fi/~saja/var_roles/role_intro.html

See http://www.cs.joensuu.fi/~saja/var_roles/try.html

See http://cs.uef.fi/~pgerdt/RAE/

See http://www.cs.joensuu.fi/~saja/var_roles/why_roles.html

See http://www.cs.joensuu.fi/~saja/var_roles/teaching.html

See http://saja.kapsi.fi/var_roles/literature.html

Ahrendt W, Bubel R, Hahnle R (2009) Integrated and tool-supported teaching of testing, debugging, and verification. In: Gibbons J, Oliveira JN (eds) Proceedings of the 2nd international conference on teaching formal methods (TFM ’09). Springer, Berlin/Heidelberg, pp 125–143

Google Scholar  

Alqadi BS, Maletic JI (2017) An empirical study of debugging patterns among novices programmers. In: Proceedings of the 2017 ACM SIGCSE technical symposium on computer science education (SIGCSE ’17). ACM, New York, pp 15–20

Arshad N (2009) Teaching programming and problem solving to CS2 students using think-alouds. SIGCSE Bull 41(1):372–376

Astrachan O, Berry G, Cox L, Mitchener G (1998) Design patterns: an essential component of CS curricula. In: Proceeding of SIGCSE, pp 153–160

Batory D, Sarvela JN, Rauschmayer A (2004) Scaling stepwise refinement. IEEE Trans Softw Eng 30(6):355–371

Bauer A, Popović Z (2017) Collaborative problem solving in an open-ended scientific discovery game. In: Proceedings of the ACM Human-Computer Interaction 1, CSCW, Article 22 (December 2017)

Ben-Ari M, Sajaniemi J (2003) Roles of variables from the perspective of computer science educators. University of Joensuu, Department of Computer Science, Technical Report, Series A-2003–6

Börstler J, Hilburn TB (2016) Team projects in computing education. ACM Trans Comput Educ 16(2), Article 4 (March 2016)

Byckling P, Sajaniemi J (2006) Roles of variables and programming skills improvement. SIGCSE Bull 38(1):413–417

Carver S, McCoy (1988) Learning and transfer of debugging skills: applying task analysis to curriculum design and assessment. In Mayer RE (ed) Teaching and learning computer programming, multiple research perspectives. Lawrence Erlbaum Associates, Inc., Chapter 11

Celepkolu M, Boyer KE (2018) The importance of producing shared code through pair programming. In: Proceedings of the 49th ACM technical symposium on computer science education (SIGCSE ’18). ACM, New York, pp 765–770

Clancy MJ, Linn M C (1999) Patterns and pedagogy. In: Proceedings of the SIGCSE’99, pp 37–42

Cosmides L, Tooby J (1997) Evolutionary psychology: a primer. Retrieved 24 October 2004, from http://www.psych.ucsb.edu/research/cep/primer.html

Dijkstra EW (1976) A discipline of programming. Prentice-Hall, Englewood Cliffs

MATH   Google Scholar  

East JP, Thomas SR, Wallingford E, Beck W, Drake J (1996) Pattern-based programming instruction. In: Proceedings of ASEE annual conference and exposition, Washington, DC

Ginat D (2003) The greedy trap and learning from mistakes. SIGCSE Bull 35(1):11–15

Ginat D (2004) Algorithmic patterns and the case of the sliding delta. SIGCSE Bull 36(2):29–33

Ginat D (2008) Learning from wrong and creative algorithm design. SIGCSE Bull 40(1):26–30

Ginat D (2009) Interleaved pattern composition and scaffolded learning. In: Proceedings of the 14th Annual ACM SIGCSE Conference on Innovation and Technology in Computer Science Education – ITiCSE ‘09, Paris, France, pp 109–113

Ginat D, Shmalo R (2013) Constructive use of errors in teaching CS1. In: Proceedings of the 44th ACM technical symposium on Computer science education (SIGCSE ’13). ACM, New York, pp 353–358

Hasni TF, Lodhi F (2011) Teaching problem solving effectively. ACM Inroads 2(3):58–62

Hazzan O, Leron U (2006) Why do we resist testing? Syst Des Front Exclus Front Cover Syst Des 3(7):20–23

Johnson DW, Johanson RT (2017) Cooperative learning. Retrieved from: https://2017.congresoinnovacion.educa.aragon.es/documents/48/David_Johnson.pdf

Jonassen DH (2000) Toward a design theory of problem solving. Educ Technol Res Dev 48(4):63–85

Kiesmüller U (2009) Diagnosing learners’ problem-solving strategies using learning environments with algorithmic problems in secondary education. Trans Comput Educ 9(3), Article 17 (September 2009), 26 pages

Laakso MJ, Malmi L, Korhonen A, Rajala T, Kaila E, Salakoski T (2008) Using roles of variables to enhance novice’s debugging work. Issues Informing Sci Inf Technol 5:281–295

Lapidot T, Hazzan O (2005) Song debugging: merging content and pedagogy in computer science education. Inroads SIGCSE Bull 37(4):79–83

Lieberman H (1997) The debugging scandal and what to do about it (special section). Comm ACM 40(4):27–29

Lishinski A, Yadav A, Enbody R, Good J (2016) The influence of problem solving abilities on Students’ performance on different assessment tasks in CS1. In: Proceedings of the 47th ACM technical symposium on computing science education (SIGCSE ’16). ACM, New York, pp 329–334

Muller O (2005) Pattern oriented instruction and the enhancement of analogical reasoning. In: Proceedings of the first International Workshop on Computer Education Research ICER ‘05, Seattle, WA, USA, pp 57–67

Muller O, Haberman B, Averbuch H (2004) (An almost) pedagogical pattern for pattern-based problem solving instruction. In: Proceedings of the 9th Annual SIGCSE Conference on Innovation and Technology in Computer Science. Education, pp 102–106

Muller O, Ginat D, Haberman B (2007) Pattern-oriented instruction and its influence on problem decomposition and solution construction. ACM SIGCSE Bull 39(3):151–155

Murphy L, Lewandowski G, McCauley R, Simon B, Thomas L, Zander C (2008) Debugging: the good, the bad, and the quirky – a qualitative analysis of novices’ strategies. SIGCSE Bull 40(1):163–167

Nagvajara P, Taskin B (2007) Design-for-debug: a vital aspect in education. In: Proceedings of the 2007 IEEE international conference on microelectronic systems education (MSE ’07). IEEE Computer Society, Washington, DC, USA, pp 65–66

Papert S (1980) Mindstorms: children, computers and powerful ideas. Basic Books Inc, New York

Polya G (1957) How to solve it. Doubleday and Co., Inc, Garden City

Polya G (1981) Mathematical discovery on understanding learning and teaching problem solving. Wiley, New York

Popper KR (1992/1959) Logic of scientific discovery. Harper and Row, New York

Proulx VK (2000) Programming patterns and design patterns in the introductory computer science course. Proc SIGCSE 32(1):80–84

Ragonis N (2012) Integrating the teaching of algorithmic patterns into computer science teacher preparation programs. In: Proceedings of the 17th ACM annual conference on Innovation and technology in computer science education (ITiCSE ’12). ACM, New York, pp 339–344

Raman K, Svore KM, Gilad-Bachrach R, Burges CJC (2012) Learning from mistakes: towards a correctable learning algorithm. In: Proceedings of the 21st ACM international conference on information and knowledge management (CIKM ’12). ACM, New York, pp 1930–1934

Reed D (1999) Incorporating problem-solving patterns in CS1. J Comput Sci Edu 13(1):6–13

Reynolds RG, Maletic JI, Porvin SE (1992) Stepwise refinement and problem solving. IEEE Softw 9(5):79–88

Robins A, Rountree J, Rountree N (2003) Learning and teaching programming: a review and discussion. Comput Sci Edu 13(2):137–172

Sajaniemi J (2005) Roles of variables and learning to program. In: Jimoyiannis A (ed) Proceedings of the 3rd Panhellenic conference didactics of informatics, University of Peloponnese, Korinthos, Greece. http://cs.joensuu.fi/~saja/var_roles/abstracts/didinf05.pdf . Accessed 3 July 2010

Santos AL, Sousa J (2017) An exploratory study of how programming instructors illustrate variables and control flow. In: Proceedings of the 17th Koli calling international conference on computing education research (Koli Calling ’17). ACM, New York, pp 173–177

Schoenfeld AH (1983) Episodes and executive decisions in mathematical problem-solving. In: Lesh R, Landaue M (eds) Acquisition of mathematics concepts and processes. Academic Press Inc, New York

Schön DA (1983) The reflective practitioner. BasicBooks

Seta K, Kajino T, Umano M, Ikeda M (2006) An ontology based reflection support system to encourage learning from mistakes. In: Deved V (ed) Proceedings of the 24th IASTED international conference on artificial intelligence and applications (AIA’06). ACTA Press, Anaheim, pp 142–149

Soloway E (1986) Learning to program = learning to construct mechanisms and explanations. CACM 29(1):850–858

Spohrer JG, Soloway E (1986) Analyzing the high frequency bugs in novice programs. In: Soloway E, Iyengar S (eds) Empirical studies of programmers. Ablex, Norwood, pp 230–251

Stoeffler K, Rosen Y, von Davier A (2017) Exploring the measurement of collaborative problem solving using a human-agent educational game. In: Proceedings of the seventh international learning analytics & knowledge conference (LAK ‘17). ACM, New York, pp 570–571

Vainio V, Sajaniemi J (2007) Factors in novice programmers’ poor tracing skills. SIGCSE Bull 39(3):236–240

Vasconcelos J (2007) Basic strategy for algorithmic problem solving. http://www.cs.jhu.edu/~jorgev/cs106/ProblemSolving.html . Accessed 2 June 2010

Vírseda R d V, Orna EP, Berbis E, Guerrero S d L (2011) A logic teaching tool based on tableaux for verification and debugging of algorithms. In: Blackburn P, van Ditmarsch H, Soler-Toscano F, Manzano M (eds) Proceedings of the third international congress conference on tools for teaching logic (TICTTL’11). Springer, Berlin/Heidelberg, pp 239–248

Von Davier AA, Halpin PF (2013) Collaborative problem solving and the assessment of cognitive skills: psychometric considerations. ETS Res Rep Ser 2013(2):1–36

Wallingford E (1996) Toward a first course based on object-oriented patterns. In: Proceedings of the SIGCSE, pp 27–31

Wirth N (1971) Program development by stepwise refinement. CACM 14(4):221–227. http://sunnyday.mit.edu/16.355/wirth-refinement.html . Accessed 13 Nov 2010

Download references

Author information

Authors and affiliations.

Department of Education in Science & Technology, Technion–Israel Institute of Technology, Haifa, Israel

Orit Hazzan & Tami Lapidot

Faculty of Education, Beit Berl College, Doar Beit Berl, Israel

Noa Ragonis

You can also search for this author in PubMed   Google Scholar

Rights and permissions

Reprints and permissions

Copyright information

© 2020 Springer Nature Switzerland AG

About this chapter

Hazzan, O., Ragonis, N., Lapidot, T. (2020). Problem-Solving Strategies. In: Guide to Teaching Computer Science. Springer, Cham. https://doi.org/10.1007/978-3-030-39360-1_8

Download citation

DOI : https://doi.org/10.1007/978-3-030-39360-1_8

Published : 06 August 2020

Publisher Name : Springer, Cham

Print ISBN : 978-3-030-39359-5

Online ISBN : 978-3-030-39360-1

eBook Packages : Computer Science Computer Science (R0)

Share this chapter

Anyone you share the following link with will be able to read this content:

Sorry, a shareable link is not currently available for this article.

Provided by the Springer Nature SharedIt content-sharing initiative

  • Publish with us

Policies and ethics

  • Find a journal
  • Track your research

What is an Algorithm? Algorithm Definition for Computer Science Beginners

Kolade Chris

If you’re a student and want to study computer science, or you’re learning to code, then there’s a chance you’ve heard of algorithms. Simply put, an algorithm is a set of instructions that performs a particular action.

Contrary to popular belief, an algorithm is not some piece of code that requires extremely advanced knowledge in order to implement. At the same time, I won't say that an algorithm is easy to implement, either. Some can be, but it depends on what you're trying to do.

In the end, the best way to get better at algorithms is by practicing them regularly.

In this article, you'll learn all about algorithms so you'll be prepared next time you encounter one, or have to write one yourself. I will also share some freeCodeCamp resources that will help you learn how to write algorithms in different languages.

What We'll Cover

What exactly is an algorithm.

  • Why Do You Need an Algorithm?

Types of Algorithms

  • Which Programming Language Is Best for Writing Algorithms? (rename)

Resources for Learning Algorithms

An algorithm is a set of steps for solving a known problem. Most algorithms are implemented to run following the four steps below:

  • take an input
  • access that input and make sure it's correct
  • show the result
  • terminate (the stage where the algorithm stop running)

Some steps of the algorithm may run repeatedly, but in the end, termination is what ends an algorithm.

For example, the algorithm below sort numbers in descending order. It loops through the numbers specified until it arranges them in descending order, then terminates when there are no more number to sort:

For a theoretical basis, for instance, an algorithm for dividing two numbers and showing the remainder could run through the steps below:

  • Step 1 : the user enters the first and second numbers – the dividend and the divisor
  • Step 2 : the algorithm written to perform the division takes in the number, then puts a division sign between the dividend and the divisor. It also checks for a remainder.
  • Step 3 : the result of the division and remainder is shown to the user
  • Step 4 : the algorithm terminates

Here's how that kind of algorithm is implemented in JavaScript:

If there's an error, the algorithm may not run, or might return the wrong output. If the programmer who wrote the algorithm took user experience into consideration, then an error handler could show an error to the user and let them know what to do.

Why do you Need an Algorithm?

If you’re one of those computer science students asking “why algorithms”, here are some reasons why you should learn about them:

Problem Solving : being able to write an algorithm improves your problem-solving capacity. It is a common belief that once you can solve a problem with one thing, you can solve problems with another closely related one. So, if you can solve problems with Python, you can solve problems with JavaScript.

Scalability : an algorithm helps your software/application/website respond appropriately to demands.

Proper Utilization of Resources: choosing the right algorithm ensures proper utilization of resources such as memory, storage, network, and others.

Algorithms in computer science can be broadly categorized into searching and sorting algorithms:

  • Sorting – selection sort, bubble sort, insertion sort, merge sort, quick sort, and so on.
  • Searching – binary search, exponential search, jump search, and so on.

But there are many types of algorithms that programers use regularly. Here are some other common algorithm types organized by category:

  • Hashing – SHA-256, SHA-1
  • Brute force – trial and error
  • Divide and conquer – merge sort algorithm
  • Greedy – Prim's algorithm, Kruskal's algorithm
  • Recursive – computer factorials

Which Programming Language Is Best for Writing Algorithms?

You can write angorithms in any programming language. There's no benefit to using one language over another.

Every language has its strengths and weaknesses, and each has unique syntax and features. So writing an algorithm might look different in one language compared to another.

But algorithms are universal concepts. So if you can write bubble sort in Python, you should also be able to write it in JavaScript or C#.

Here are some videos from the freeCodeCamp YouTube channel that can help you learn algorithms effectively:

  • Algorithms and Data Structures Tutorial - Full Course for Beginners
  • Algorithms in Python – Full Course for Beginners
  • Data Structures Easy to Advanced Course - Full Tutorial from a Google Engineer
  • Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges
  • Understanding Sorting Algorithms

Also, the interactive JavaScript Algorithms and Data Structures Certification on freeCodeCamp can give you a crash course in algorithmic thinking in JavaScript.

In this article, we went over what an algorithm is, their types, and resources for learning algorithms.

If you read this far, the next thing you should do is start learning algorithms with one or more of the resources listed in this article.

Thank you for reading.

Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

1: Algorithmic Problem Solving

  • Last updated
  • Save as PDF
  • Page ID 46789

  • Harrison Njoroge
  • African Virtual University

Unit Objectives

Upon completion of this unit the learner should be able to:

  • describe an algorithm
  • explain the relationship between data and algorithm
  • outline the characteristics of algorithms
  • apply pseudo codes and flowcharts to represent algorithms

Unit Introduction

This unit introduces learners to data structures and algorithm course. The unit is on the different data structures and their algorithms that can help implement the different data structures in the computer. The application of the different data structures is presented by using examples of algorithms and which are not confined to a particular computer programming language.

  • Data: the structural representation of logical relationships between elements of data
  • Algorithm: finite sequence of steps for accomplishing some computational task
  • Pseudo code: an informal high-level description of the operating principle of a computer program or other algorithm
  • Flow chart: diagrammatic representation illustrates a solution model to a given problem.

Learning Activities

  • 1.1: Activity 1 - Introduction to Algorithms and Problem Solving In this learning activity section, the learner will be introduced to algorithms and how to write algorithms to solve tasks faced by learners or everyday problems. Examples of the algorithm are also provided with a specific application to everyday problems that the learner is familiar with. The learners will particularly learn what is an algorithm, the process of developing a solution for a given task, and finally examples of application of the algorithms are given.
  • 1.2: Activity 2 - The characteristics of an algorithm This section introduces the learners to the characteristics of algorithms. These characteristics make the learner become aware of what to ensure is basic, present and mandatory for any algorithm to qualify to be one. It also exposes the learner to what to expect from an algorithm to achieve or indicate. Key expectations are: the fact that an algorithm must be exact, terminate, effective, general among others.
  • 1.3: Activity 3 - Using pseudo-codes and flowcharts to represent algorithms The student will learn how to design an algorithm using either a pseudo code or flowchart. Pseudo code is a mixture of English like statements, some mathematical notations and selected keywords from a programming language. It is one of the tools used to design and develop the solution to a task or problem. Pseudo codes have different ways of representing the same thing and emphasis is on the clarity and not style.
  • 1.4: Unit Summary In this unit, you have seen what an algorithm is. Based on this knowledge, you should now be able to characterize an algorithm by stating its properties. We have explored the different ways of representing an algorithm such as using human language, pseudo codes and flow chart. You should now be able to present solutions to problems in form of an algorithm.
  • School Guide
  • Class 8 Syllabus
  • Maths Notes Class 8
  • Science Notes Class 8
  • History Notes Class 8
  • Geography Notes Class 8
  • Civics Notes Class 8
  • NCERT Soln. Class 8 Maths
  • RD Sharma Soln. Class 8
  • Math Formulas Class 8
  • Working with Layers in Flash
  • What is Download and Upload Speed?
  • What is the Impact of E-Commerce on the Society?
  • Factors Affecting Video Conferencing
  • Add Text with Horizontal Type Tool in Photoshop
  • What Factors one should Keep in Mind while doing E-Commerce?
  • Audio and Video Conferencing
  • What is EDI (Electronic Data Interchange)?
  • How to Use the Timeline in Animate?
  • Benefits of Video Conferencing
  • How to Use Frames and Keyframes in Flash?
  • Types of Animations in Flash
  • How to Create a Shape Tween in Flash?
  • What is Chatting? - Definition, Types, Platforms, Risks
  • What is E-Commerce and E-Greetings?
  • Preparing Files for Web Output in Photoshop
  • Introduction to Macromedia Flash 8
  • How to Use the Rectangle Tool in Photoshop?
  • How to Create a Motion Tween in Flash?

How to Use Algorithms to Solve Problems?

An algorithm is a process or set of rules which must be followed to complete a particular task. This is basically the step-by-step procedure to complete any task. All the tasks are followed a particular algorithm, from making a cup of tea to make high scalable software. This is the way to divide a task into several parts. If we draw an algorithm to complete a task then the task will be easier to complete.

The algorithm is used for,

  • To develop a framework for instructing computers.
  • Introduced notation of basic functions to perform basic tasks.
  • For defining and describing a big problem in small parts, so that it is very easy to execute.

Characteristics of Algorithm

  • An algorithm should be defined clearly.
  • An algorithm should produce at least one output.
  • An algorithm should have zero or more inputs.
  • An algorithm should be executed and finished in finite number of steps.
  • An algorithm should be basic and easy to perform.
  • Each step started with a specific indentation like, “Step-1”,
  • There must be “Start” as the first step and “End” as the last step of the algorithm.

Let’s take an example to make a cup of tea,

Step 1: Start

Step 2: Take some water in a bowl.

Step 3: Put the water on a gas burner .

Step 4: Turn on the gas burner 

Step 5: Wait for some time until the water is boiled.  

Step 6: Add some tea leaves to the water according to the requirement.

Step 7: Then again wait for some time until the water is getting colorful as tea.

Step 8: Then add some sugar according to taste.

Step 9: Again wait for some time until the sugar is melted.

Step 10: Turn off the gas burner and serve the tea in cups with biscuits.

Step 11: End

Here is an algorithm for making a cup of tea. This is the same for computer science problems.

There are some basics steps to make an algorithm:

  • Start – Start the algorithm
  • Input – Take the input for values in which the algorithm will execute.
  • Conditions – Perform some conditions on the inputs to get the desired output.
  • Output – Printing the outputs.
  • End – End the execution.

Let’s take some examples of algorithms for computer science problems.

Example 1. Swap two numbers with a third variable  

Step 1: Start Step 2: Take 2 numbers as input. Step 3: Declare another variable as “temp”. Step 4: Store the first variable to “temp”. Step 5: Store the second variable to the First variable. Step 6: Store the “temp” variable to the 2nd variable. Step 7: Print the First and second variables. Step 8: End

Example 2. Find the area of a rectangle

Step 1: Start Step 2: Take the Height and Width of the rectangle as input. Step 3: Declare a variable as “area” Step 4: Multiply Height and Width Step 5: Store the multiplication to “Area”, (its look like area = Height x Width) Step 6: Print “area”; Step 7: End

Example 3. Find the greatest between 3 numbers.

Step 1: Start Step 2: Take 3 numbers as input, say A, B, and C. Step 3: Check if(A>B and A>C) Step 4: Then A is greater Step 5: Print A Step 6 : Else Step 7: Check if(B>A and B>C) Step 8: Then B is greater Step 9: Print B Step 10: Else C is greater Step 11 : Print C Step 12: End

Advantages of Algorithm

  • An algorithm uses a definite procedure.
  • It is easy to understand because it is a step-by-step definition.
  • The algorithm is easy to debug if there is any error happens.
  • It is not dependent on any programming language
  • It is easier for a programmer to convert it into an actual program because the algorithm divides a problem into smaller parts.

Disadvantages of Algorithms

  • An algorithm is Time-consuming, there is specific time complexity for different algorithms.
  • Large tasks are difficult to solve in Algorithms because the time complexity may be higher, so programmers have to find a good efficient way to solve that task.
  • Looping and branching are difficult to define in algorithms.

Please Login to comment...

Similar reads.

  • School Learning
  • School Programming
  • CBSE Exam Format Changed for Class 11-12: Focus On Concept Application Questions
  • 10 Best Waze Alternatives in 2024 (Free)
  • 10 Best Squarespace Alternatives in 2024 (Free)
  • Top 10 Owler Alternatives & Competitors in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Forgot password? New user? Sign up

Existing user? Log in

  • Number Theory
  • Probability
  • Everyday Math
  • Classical Mechanics
  • Electricity and Magnetism

Computer Science

  • Quantitative Finance

Take a guided, problem-solving based approach to learning Computer Science. These compilations provide unique perspectives and applications you won't find anywhere else.

Computer Science Fundamentals

What's inside.

  • Tools of Computer Science
  • Computational Problem Solving
  • Algorithmic Thinking

Algorithm Fundamentals

  • Building Blocks
  • Array Algorithms
  • The Speed of Algorithms
  • Stable Matching

Programming with Python

  • Introduction
  • String Manipulation
  • Loops, Functions and Arguments

Community Wiki

Browse through thousands of Computer Science wikis written by our community of experts.

Types and Data Structures

  • Abstract Data Types
  • Array (ADT)
  • Double Ended Queues
  • Associative Arrays
  • Priority Queues
  • Array (Data Structure)
  • Disjoint-set Data Structure (Union-Find)
  • Dynamic Array
  • Linked List
  • Unrolled Linked List
  • Hash Tables
  • Bloom Filter
  • Cuckoo Filter
  • Merkle Tree
  • Recursive Backtracking
  • Fenwick Tree
  • Binary Search Trees
  • Red-Black Tree
  • Scapegoat Tree
  • Binary Heap
  • Binomial Heap
  • Fibonacci Heap
  • Pairing Heap
  • Graph implementation and representation
  • Adjacency Matrix
  • Spanning Trees
  • Social Networks
  • Kruskal's Algorithm
  • Regular Expressions
  • Divide and Conquer
  • Greedy Algorithms
  • Randomized Algorithms
  • Complexity Theory
  • Big O Notation
  • Master Theorem
  • Amortized Analysis
  • Complexity Classes
  • P versus NP
  • Dynamic Programming
  • Backpack Problem
  • Egg Dropping
  • Fast Fibonacci Transform
  • Karatsuba Algorithm
  • Sorting Algorithms
  • Insertion Sort
  • Bubble Sort
  • Counting Sort
  • Median-finding Algorithm
  • Binary Search
  • Depth-First Search (DFS)
  • Breadth-First Search (BFS)
  • Shortest Path Algorithms
  • Dijkstra's Shortest Path Algorithm
  • Bellman-Ford Algorithm
  • Floyd-Warshall Algorithm
  • Johnson's Algorithm
  • Matching (Graph Theory)
  • Matching Algorithms (Graph Theory)
  • Flow Network
  • Max-flow Min-cut Algorithm
  • Ford-Fulkerson Algorithm
  • Edmonds-Karp Algorithm
  • Shunting Yard Algorithm
  • Rabin-Karp Algorithm
  • Knuth-Morris-Pratt Algorithm
  • Basic Shapes, Polygons, Trigonometry
  • Convex Hull
  • Finite State Machines
  • Turing Machines
  • Halting Problem
  • Kolmogorov Complexity
  • Traveling Salesperson Problem
  • Pushdown Automata
  • Regular Languages
  • Context Free Grammars
  • Context Free Languages
  • Signals and Systems
  • Linear Time Invariant Systems
  • Predicting System Behavior

Programming Languages

  • Subroutines
  • List comprehension
  • Primality Testing
  • Pattern matching
  • Logic Gates
  • Control Flow Statements
  • Object-Oriented Programming
  • Classes (OOP)
  • Methods (OOP)

Cryptography and Simulations

  • Caesar Cipher
  • Vigenère Cipher
  • RSA Encryption
  • Enigma Machine
  • Diffie-Hellman
  • Knapsack Cryptosystem
  • Secure Hash Algorithms
  • Entropy (Information Theory)
  • Huffman Code
  • Error correcting codes
  • Symmetric Ciphers
  • Inverse Transform Sampling
  • Monte-Carlo Simulation
  • Genetic Algorithms
  • Programming Blackjack
  • Machine Learning
  • Supervised Learning
  • Unsupervised Learning
  • Feature Vector
  • Naive Bayes Classifier
  • K-nearest Neighbors
  • Support Vector Machines
  • Principal Component Analysis
  • Ridge Regression
  • k-Means Clustering
  • Markov Chains
  • Hidden Markov Models
  • Gaussian Mixture Model
  • Collaborative Filtering
  • Artificial Neural Network
  • Feedforward Neural Networks
  • Backpropagation
  • Recurrent Neural Network

Problem Loading...

Note Loading...

Set Loading...

If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

To log in and use all the features of Khan Academy, please enable JavaScript in your browser.

AP®︎/College Computer Science Principles

Course: ap®︎/college computer science principles   >   unit 4, using heuristics.

  • Undecidable problems
  • Solving hard problems

Traveling Salesperson Problem

The brute force approach, developing a heuristic, the nearest-neighbor heuristic, heuristics everywhere, want to join the conversation.

  • Upvote Button navigates to signup page
  • Downvote Button navigates to signup page
  • Flag Button navigates to signup page

Great Answer

Chapter: Introduction to the Design and Analysis of Algorithms

Fundamentals of Algorithmic Problem Solving

Let us start by reiterating an important point made in the introduction to this chapter:

We can consider algorithms to be procedural solutions to problems.

These solutions are not answers but specific instructions for getting answers. It is this emphasis on precisely defined constructive procedures that makes computer science distinct from other disciplines. In particular, this distinguishes it from the-oretical mathematics, whose practitioners are typically satisfied with just proving the existence of a solution to a problem and, possibly, investigating the solution’s properties.

We now list and briefly discuss a sequence of steps one typically goes through in designing and analyzing an algorithm (Figure 1.2).

Understanding the Problem

From a practical perspective, the first thing you need to do before designing an algorithm is to understand completely the problem given. Read the problem’s description carefully and ask questions if you have any doubts about the problem, do a few small examples by hand, think about special cases, and ask questions again if needed.

There are a few types of problems that arise in computing applications quite often. We review them in the next section. If the problem in question is one of them, you might be able to use a known algorithm for solving it. Of course, it helps to understand how such an algorithm works and to know its strengths and weaknesses, especially if you have to choose among several available algorithms. But often you will not find a readily available algorithm and will have to design your own. The sequence of steps outlined in this section should help you in this exciting but not always easy task.

An input to an algorithm specifies an instance of the problem the algorithm solves. It is very important to specify exactly the set of instances the algorithm needs to handle. (As an example, recall the variations in the set of instances for the three greatest common divisor algorithms discussed in the previous section.) If you fail to do this, your algorithm may work correctly for a majority of inputs but crash on some “boundary” value. Remember that a correct algorithm is not one that works most of the time, but one that works correctly for all legitimate inputs.

Do not skimp on this first step of the algorithmic problem-solving process; otherwise, you will run the risk of unnecessary rework.

Ascertaining the Capabilities of the Computational Device

Once you completely understand a problem, you need to ascertain the capabilities of the computational device the algorithm is intended for. The vast majority of 

algorithmic problem solving computer science

algorithms in use today are still destined to be programmed for a computer closely resembling the von Neumann machine—a computer architecture outlined by the prominent Hungarian-American mathematician John von Neumann (1903– 1957), in collaboration with A. Burks and H. Goldstine, in 1946. The essence of this architecture is captured by the so-called random-access machine ( RAM ). Its central assumption is that instructions are executed one after another, one operation at a time. Accordingly, algorithms designed to be executed on such machines are called sequential algorithms .

The central assumption of the RAM model does not hold for some newer computers that can execute operations concurrently, i.e., in parallel. Algorithms that take advantage of this capability are called parallel algorithms . Still, studying the classic techniques for design and analysis of algorithms under the RAM model remains the cornerstone of algorithmics for the foreseeable future.

Should you worry about the speed and amount of memory of a computer at your disposal? If you are designing an algorithm as a scientific exercise, the answer is a qualified no. As you will see in Section 2.1, most computer scientists prefer to study algorithms in terms independent of specification parameters for a particular computer. If you are designing an algorithm as a practical tool, the answer may depend on a problem you need to solve. Even the “slow” computers of today are almost unimaginably fast. Consequently, in many situations you need not worry about a computer being too slow for the task. There are important problems, however, that are very complex by their nature, or have to process huge volumes of data, or deal with applications where the time is critical. In such situations, it is imperative to be aware of the speed and memory available on a particular computer system.

Choosing between Exact and Approximate Problem Solving

The next principal decision is to choose between solving the problem exactly or solving it approximately. In the former case, an algorithm is called an exact algo-rithm ; in the latter case, an algorithm is called an approximation algorithm . Why would one opt for an approximation algorithm? First, there are important prob-lems that simply cannot be solved exactly for most of their instances; examples include extracting square roots, solving nonlinear equations, and evaluating def-inite integrals. Second, available algorithms for solving a problem exactly can be unacceptably slow because of the problem’s intrinsic complexity. This happens, in particular, for many problems involving a very large number of choices; you will see examples of such difficult problems in Chapters 3, 11, and 12. Third, an ap-proximation algorithm can be a part of a more sophisticated algorithm that solves a problem exactly.

Algorithm Design Techniques

Now, with all the components of the algorithmic problem solving in place, how do you design an algorithm to solve a given problem? This is the main question this book seeks to answer by teaching you several general design techniques.

What is an algorithm design technique?

An algorithm design technique (or “strategy” or “paradigm”) is a general approach to solving problems algorithmically that is applicable to a variety of problems from different areas of computing.

Check this book’s table of contents and you will see that a majority of its chapters are devoted to individual design techniques. They distill a few key ideas that have proven to be useful in designing algorithms. Learning these techniques is of utmost importance for the following reasons.

First, they provide guidance for designing algorithms for new problems, i.e., problems for which there is no known satisfactory algorithm. Therefore—to use the language of a famous proverb—learning such techniques is akin to learning to fish as opposed to being given a fish caught by somebody else. It is not true, of course, that each of these general techniques will be necessarily applicable to every problem you may encounter. But taken together, they do constitute a powerful collection of tools that you will find quite handy in your studies and work.

Second, algorithms are the cornerstone of computer science. Every science is interested in classifying its principal subject, and computer science is no exception. Algorithm design techniques make it possible to classify algorithms according to an underlying design idea; therefore, they can serve as a natural way to both categorize and study algorithms.

Designing an Algorithm and Data Structures

While the algorithm design techniques do provide a powerful set of general ap-proaches to algorithmic problem solving, designing an algorithm for a particular problem may still be a challenging task. Some design techniques can be simply inapplicable to the problem in question. Sometimes, several techniques need to be combined, and there are algorithms that are hard to pinpoint as applications of the known design techniques. Even when a particular design technique is ap-plicable, getting an algorithm often requires a nontrivial ingenuity on the part of the algorithm designer. With practice, both tasks—choosing among the general techniques and applying them—get easier, but they are rarely easy.

Of course, one should pay close attention to choosing data structures appro-priate for the operations performed by the algorithm. For example, the sieve of Eratosthenes introduced in Section 1.1 would run longer if we used a linked list instead of an array in its implementation (why?). Also note that some of the al-gorithm design techniques discussed in Chapters 6 and 7 depend intimately on structuring or restructuring data specifying a problem’s instance. Many years ago, an influential textbook proclaimed the fundamental importance of both algo-rithms and data structures for computer programming by its very title: Algorithms + Data Structures = Programs [Wir76]. In the new world of object-oriented programming, data structures remain crucially important for both design and analysis of algorithms. We review basic data structures in Section 1.4.

Methods of Specifying an Algorithm

Once you have designed an algorithm, you need to specify it in some fashion. In Section 1.1, to give you an example, Euclid’s algorithm is described in words (in a free and also a step-by-step form) and in pseudocode. These are the two options that are most widely used nowadays for specifying algorithms.

Using a natural language has an obvious appeal; however, the inherent ambi-guity of any natural language makes a succinct and clear description of algorithms surprisingly difficult. Nevertheless, being able to do this is an important skill that you should strive to develop in the process of learning algorithms.

Pseudocode is a mixture of a natural language and programming language-like constructs. Pseudocode is usually more precise than natural language, and its usage often yields more succinct algorithm descriptions. Surprisingly, computer scientists have never agreed on a single form of pseudocode, leaving textbook authors with a need to design their own “dialects.” Fortunately, these dialects are so close to each other that anyone familiar with a modern programming language should be able to understand them all.

This book’s dialect was selected to cause minimal difficulty for a reader. For the sake of simplicity, we omit declarations of variables and use indentation to show the scope of such statements as for , if , and while . As you saw in the previous section, we use an arrow “ ← ” for the assignment operation and two slashes “ // ” for comments.

In the earlier days of computing, the dominant vehicle for specifying algo-rithms was a flowchart , a method of expressing an algorithm by a collection of connected geometric shapes containing descriptions of the algorithm’s steps. This representation technique has proved to be inconvenient for all but very simple algorithms; nowadays, it can be found only in old algorithm books.

The state of the art of computing has not yet reached a point where an algorithm’s description—be it in a natural language or pseudocode—can be fed into an electronic computer directly. Instead, it needs to be converted into a computer program written in a particular computer language. We can look at such a program as yet another way of specifying the algorithm, although it is preferable to consider it as the algorithm’s implementation.

Proving an Algorithm’s Correctness

Once an algorithm has been specified, you have to prove its correctness . That is, you have to prove that the algorithm yields a required result for every legitimate input in a finite amount of time. For example, the correctness of Euclid’s algorithm for computing the greatest common divisor stems from the correctness of the equality gcd (m, n) = gcd (n, m mod n) (which, in turn, needs a proof; see Problem 7 in Exercises 1.1), the simple observation that the second integer gets smaller on every iteration of the algorithm, and the fact that the algorithm stops when the second integer becomes 0.

For some algorithms, a proof of correctness is quite easy; for others, it can be quite complex. A common technique for proving correctness is to use mathemati-cal induction because an algorithm’s iterations provide a natural sequence of steps needed for such proofs. It might be worth mentioning that although tracing the algorithm’s performance for a few specific inputs can be a very worthwhile activ-ity, it cannot prove the algorithm’s correctness conclusively. But in order to show that an algorithm is incorrect, you need just one instance of its input for which the algorithm fails.

The notion of correctness for approximation algorithms is less straightforward than it is for exact algorithms. For an approximation algorithm, we usually would like to be able to show that the error produced by the algorithm does not exceed a predefined limit. You can find examples of such investigations in Chapter 12.

Analyzing an Algorithm

We usually want our algorithms to possess several qualities. After correctness, by far the most important is efficiency . In fact, there are two kinds of algorithm efficiency: time efficiency , indicating how fast the algorithm runs, and space ef-ficiency , indicating how much extra memory it uses. A general framework and specific techniques for analyzing an algorithm’s efficiency appear in Chapter 2.

Another desirable characteristic of an algorithm is simplicity . Unlike effi-ciency, which can be precisely defined and investigated with mathematical rigor, simplicity, like beauty, is to a considerable degree in the eye of the beholder. For example, most people would agree that Euclid’s algorithm is simpler than the middle-school procedure for computing gcd (m, n) , but it is not clear whether Eu-clid’s algorithm is simpler than the consecutive integer checking algorithm. Still, simplicity is an important algorithm characteristic to strive for. Why? Because sim-pler algorithms are easier to understand and easier to program; consequently, the resulting programs usually contain fewer bugs. There is also the undeniable aes-thetic appeal of simplicity. Sometimes simpler algorithms are also more efficient than more complicated alternatives. Unfortunately, it is not always true, in which case a judicious compromise needs to be made.

Yet another desirable characteristic of an algorithm is generality . There are, in fact, two issues here: generality of the problem the algorithm solves and the set of inputs it accepts. On the first issue, note that it is sometimes easier to design an algorithm for a problem posed in more general terms. Consider, for example, the problem of determining whether two integers are relatively prime, i.e., whether their only common divisor is equal to 1. It is easier to design an algorithm for a more general problem of computing the greatest common divisor of two integers and, to solve the former problem, check whether the gcd is 1 or not. There are situations, however, where designing a more general algorithm is unnecessary or difficult or even impossible. For example, it is unnecessary to sort a list of n numbers to find its median, which is its n/ 2 th smallest element. To give another example, the standard formula for roots of a quadratic equation cannot be generalized to handle polynomials of arbitrary degrees.

As to the set of inputs, your main concern should be designing an algorithm that can handle a set of inputs that is natural for the problem at hand. For example, excluding integers equal to 1 as possible inputs for a greatest common divisor algorithm would be quite unnatural. On the other hand, although the standard formula for the roots of a quadratic equation holds for complex coefficients, we would normally not implement it on this level of generality unless this capability is explicitly required.

If you are not satisfied with the algorithm’s efficiency, simplicity, or generality, you must return to the drawing board and redesign the algorithm. In fact, even if your evaluation is positive, it is still worth searching for other algorithmic solutions. Recall the three different algorithms in the previous section for computing the greatest common divisor: generally, you should not expect to get the best algorithm on the first try. At the very least, you should try to fine-tune the algorithm you already have. For example, we made several improvements in our implementation of the sieve of Eratosthenes compared with its initial outline in Section 1.1. (Can you identify them?) You will do well if you keep in mind the following observation of Antoine de Saint-Exupery,´ the French writer, pilot, and aircraft designer: “A designer knows he has arrived at perfection not when there is no longer anything to add, but when there is no longer anything to take away.” 1

Coding an Algorithm

  Most algorithms are destined to be ultimately implemented as computer pro-grams. Programming an algorithm presents both a peril and an opportunity. The peril lies in the possibility of making the transition from an algorithm to a pro-gram either incorrectly or very inefficiently. Some influential computer scientists strongly believe that unless the correctness of a computer program is proven with full mathematical rigor, the program cannot be considered correct. They have developed special techniques for doing such proofs (see [Gri81]), but the power of these techniques of formal verification is limited so far to very small programs.

As a practical matter, the validity of programs is still established by testing. Testing of computer programs is an art rather than a science, but that does not mean that there is nothing in it to learn. Look up books devoted to testing and debugging; even more important, test and debug your program thoroughly whenever you implement an algorithm.

Also note that throughout the book, we assume that inputs to algorithms belong to the specified sets and hence require no verification. When implementing algorithms as programs to be used in actual applications, you should provide such verifications.

Of course, implementing an algorithm correctly is necessary but not sufficient: you would not like to diminish your algorithm’s power by an inefficient implemen-tation. Modern compilers do provide a certain safety net in this regard, especially when they are used in their code optimization mode. Still, you need to be aware of such standard tricks as computing a loop’s invariant (an expression that does not change its value) outside the loop, collecting common subexpressions, replac-ing expensive operations by cheap ones, and so on. (See [Ker99] and [Ben00] for a good discussion of code tuning and other issues related to algorithm program-ming.) Typically, such improvements can speed up a program only by a constant factor, whereas a better algorithm can make a difference in running time by orders of magnitude. But once an algorithm is selected, a 10–50% speedup may be worth an effort.

A working program provides an additional opportunity in allowing an em-pirical analysis of the underlying algorithm. Such an analysis is based on timing the program on several inputs and then analyzing the results obtained. We dis-cuss the advantages and disadvantages of this approach to analyzing algorithms in Section 2.6.

In conclusion, let us emphasize again the main lesson of the process depicted in Figure 1.2:

As a rule, a good algorithm is a result of repeated effort and rework.

Even if you have been fortunate enough to get an algorithmic idea that seems perfect, you should still try to see whether it can be improved.

Actually, this is good news since it makes the ultimate result so much more enjoyable. (Yes, I did think of naming this book The Joy of Algorithms .) On the other hand, how does one know when to stop? In the real world, more often than not a project’s schedule or the impatience of your boss will stop you. And so it should be: perfection is expensive and in fact not always called for. Designing an algorithm is an engineering-like activity that calls for compromises among competing goals under the constraints of available resources, with the designer’s time being one of the resources.

In the academic world, the question leads to an interesting but usually difficult investigation of an algorithm’s optimality . Actually, this question is not about the efficiency of an algorithm but about the complexity of the problem it solves: What is the minimum amount of effort any algorithm will need to exert to solve the problem? For some problems, the answer to this question is known. For example, any algorithm that sorts an array by comparing values of its elements needs about n log 2 n comparisons for some arrays of size n (see Section 11.2). But for many seemingly easy problems such as integer multiplication, computer scientists do not yet have a final answer.

Another important issue of algorithmic problem solving is the question of whether or not every problem can be solved by an algorithm. We are not talking here about problems that do not have a solution, such as finding real roots of a quadratic equation with a negative discriminant. For such cases, an output indicating that the problem does not have a solution is all we can and should expect from an algorithm. Nor are we talking about ambiguously stated problems. Even some unambiguous problems that must have a simple yes or no answer are “undecidable,” i.e., unsolvable by any algorithm. An important example of such a problem appears in Section 11.3. Fortunately, a vast majority of problems in practical computing can be solved by an algorithm.

Before leaving this section, let us be sure that you do not have the misconception—possibly caused by the somewhat mechanical nature of the diagram of Figure 1.2—that designing an algorithm is a dull activity. There is nothing further from the truth: inventing (or discovering?) algorithms is a very creative and rewarding process. This book is designed to convince you that this is the case.

Exercises 1.2

             Old World puzzle A peasant finds himself on a riverbank with a wolf, a goat, and a head of cabbage. He needs to transport all three to the other side of the river in his boat. However, the boat has room for only the peasant himself and one other item (either the wolf, the goat, or the cabbage). In his absence, the wolf would eat the goat, and the goat would eat the cabbage. Solve this problem for the peasant or prove it has no solution. (Note: The peasant is a vegetarian but does not like cabbage and hence can eat neither the goat nor the cabbage to help him solve the problem. And it goes without saying that the wolf is a protected species.)

            New World puzzle There are four people who want to cross a rickety bridge; they all begin on the same side. You have 17 minutes to get them all across to the other side. It is night, and they have one flashlight. A maximum of two people can cross the bridge at one time. Any party that crosses, either one or two people, must have the flashlight with them. The flashlight must be walked back and forth; it cannot be thrown, for example. Person 1 takes 1 minute to cross the bridge, person 2 takes 2 minutes, person 3 takes 5 minutes, and person 4 takes 10 minutes. A pair must walk together at the rate of the slower person’s pace. (Note: According to a rumor on the Internet, interviewers at a well-known software company located near Seattle have given this problem to interviewees.)

            Which of the following formulas can be considered an algorithm for comput-ing the area of a triangle whose side lengths are given positive numbers a , b , and c ?

algorithmic problem solving computer science

            Write pseudocode for an algorithm for finding real roots of equation ax 2 + bx + c = 0 for arbitrary real coefficients a, b, and c. (You may assume the availability of the square root function sqrt (x). )

            Describe the standard algorithm for finding the binary representation of a positive decimal integer

                     in English.

                     in pseudocode.

            Describe the algorithm used by your favorite ATM machine in dispensing cash. (You may give your description in either English or pseudocode, which-ever you find more convenient.)

            a.  Can the problem of computing the number π be solved exactly?

                     How many instances does this problem have?

Look up an algorithm for this problem on the Internet.

                                                                    Give an example of a problem other than computing the greatest common divisor for which you know more than one algorithm. Which of them is simpler? Which is more efficient?

                                                                    Consider the following algorithm for finding the distance between the two closest elements in an array of numbers.

ALGORITHM                       MinDistance (A [0 ..n − 1] )

//Input: Array A [0 ..n − 1] of numbers

//Output: Minimum distance between two of its elements dmin ← ∞

for i ← 0 to n − 1 do

for j ← 0 to n − 1 do

if i  = j and |A[i] − A[j ]| < dmin dmin ← |A[i] − A[j ]|

return dmin

Make as many improvements as you can in this algorithmic solution to the problem. If you need to, you may change the algorithm altogether; if not, improve the implementation given.

One of the most influential books on problem solving, titled How To Solve It [Pol57], was written by the Hungarian-American mathematician George Polya´ (1887–1985). Polya´ summarized his ideas in a four-point summary. Find this summary on the Internet or, better yet, in his book, and compare it with the plan outlined in Section 1.2. What do they have in common? How are they different?

Related Topics

Privacy Policy , Terms and Conditions , DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.

Code With C

The Way to Programming

  • C Tutorials
  • Java Tutorials
  • Python Tutorials
  • PHP Tutorials
  • Java Projects

Understanding Algorithms: The Foundation of Computer Science

CodeLikeAGirl

Hey there, my tech-savvy pals! Today, we are delving into the exhilarating realm of algorithms, the cornerstone of Computer Science! 🖥️ Let’s unravel the mysteries behind the magic of algorithms and explore their quirks and perks in the digital universe! Buckle up for a humorous ride through the world of problem-solving geniuses and resource-saving gurus! 🚀

Importance of Algorithms

Efficiency in problem-solving.

Algorithms are like the secret sauce in your grandma’s recipe, but for tech geeks! They are the brains behind solving those mind-boggling puzzles that make others go, “Wait, whaaat?” Imagine having a universal problem-solving genie at your beck and call – that’s algorithms for you! They slice through problems like a hot knife through butter (okay, maybe a warm knife on some tough days 😅)!

Optimization of Resources

Why waste time, energy, and precious resources when you can have algorithms do the heavy lifting for you? These digital superheroes streamline processes, making them as smooth as jazz in a summer breeze. They are the maestros of efficiency, turning chaos into organized symphonies! Who doesn’t love a good ol’ resource-saving maestro, right? 🎵

Types of Algorithms

Searching algorithms.

Ever lost your keys and turned your room upside down searching for them? Well, searching algorithms are here to save the day without the chaos! They hunt down that elusive data faster than you can say “Abracadabra!” 🎩 Get ready to bid farewell to your searching woes with these nifty algorithms!

Sorting Algorithms

Sorting algorithms are like the neat freaks of the digital world – they love putting things in order! From arranging numbers in ascending order to alphabetizing your favorite tunes, they’ve got your back! Say goodbye to the mayhem of unsorted data and embrace the tranquility of sorted bliss! 🎶

Algorithm Design Techniques

Divide and conquer.

Divide and conquer is not just a strategy in war; it’s the holy grail of algorithm design! Break down complex problems into smaller, more manageable chunks and conquer them like a boss! It’s like splitting a giant pizza into slices – easier to handle and oh-so-satisfying to devour! 🍕

Greedy Algorithms

Who knew being “greedy” could be a good thing in the algorithmic universe? Greedy algorithms make decisions based on immediate benefit, kind of like grabbing the last slice of pizza without a second thought (we’ve all been there, right?). They might sound selfish, but hey, they get the job done efficiently! 🍕

Algorithm Complexity Analysis

Time complexity.

How fast can an algorithm boogie through a task? That’s where time complexity struts in! It measures how quickly an algorithm runs as the input size grows. Think of it like comparing a snail’s pace to the speed of light – time complexity tells us which algorithm is the Flash in the digital universe! 💨

Space Complexity

Just like tidying up your room, algorithms also need space to stretch their legs! Space complexity keeps tabs on how much memory an algorithm munches on as it struts its stuff. It’s like making sure your algorithm has enough elbow room to dance without bumping into others – space efficiency at its finest! 💃

Practical Applications of Algorithms

Data compression.

Say goodbye to bulky files and hello to algorithmic magic with data compression ! Algorithms shrink those oversized files into byte-sized bits, making storage a breeze. It’s like having a magical wardrobe that fits your entire wardrobe – talk about space-saving wizardry! 🧙‍♂️

Machine Learning Algorithms

Machine learning algorithms are the cool cats of the tech town! They learn from data, predict outcomes, and make decisions – all without breaking a sweat! From recommending your next binge-watch to detecting spam emails, these algorithms have your back. They’re the digital gurus shaping the future – one byte at a time! 🤖

Phew! That was quite the algorithmic rollercoaster, wasn’t it? From problem-solving wizards to efficiency maestros, algorithms are the unsung heroes of the digital realm! So, the next time you marvel at the wonders of technology, remember – algorithms are the invisible hands shaping our digital universe! 🌌

Overall, diving into the realm of algorithms has been both enlightening and exhilarating! Thanks for joining me on this humorous escapade through the digital wonders of algorithmic magic. Remember, folks, when life throws you algorithms, embrace them like a warm hug from a tech-savvy friend! Stay curious, stay nerdy, and keep algorithmically awesome! Until next time, happy coding and may your algorithms always run with wit and charm! 🤓✨

Thank you for embarking on this algorithmic adventure with me! Keep smiling and coding away, my digital pals! Stay tuned for more tech-tastic thrills and spills in the wild world of algorithms! Adios! 👋🚀

Understanding Algorithms: The Foundation of Computer Science

Program Code – Understanding Algorithms: The Foundation of Computer Science

Code output:, ### code explanation:.

This program showcases the implementation and usage of two fundamental algorithms in computer science : Bubble Sort and Binary Search. Let’s dive into how each part of the code contributes to achieving this:

  • Bubble Sort Algorithm : The bubble_sort function sorts an array by repeatedly swapping adjacent elements if they are in the wrong order. This process repeats until no more swaps are needed, indicating the array is sorted. The algorithm iterates over the array, starting from the first index to the penultimate one, comparing adjacent items and swapping them if they’re not in the desired order (ascending in this case). It’s known for its simplicity but is not the most efficient for large datasets.
  • Binary Search Algorithm : The binary_search function searches for a specific element ( x ) in a sorted array by repeatedly dividing in half the portion of the list that could contain the desired element until narrowing down the possibilities to just one. It checks whether the element at the midpoint is the target. If it’s not, it decides whether to proceed with the left or the right half based on whether the target is less or more than the midpoint. This method greatly reduces the number of comparisons necessary, making it efficient for large datasets.
  • The main block of the code first sorts an unsorted array using the Bubble Sort method. After sorting, it proceeds to search for an element ( x=22 ) using the Binary Search algorithm. It prints the sorted array and the index of the searched element if found, or indicates its absence.

This example effectively demonstrates the utility and working of both algorithms, highlighting the importance of understanding such fundamental algorithms that serve as the building blocks for more complex operations and applications in the field of Computer Science.

Frequently Asked Questions about Understanding Algorithms: The Foundation of Computer Science

What is the significance of algorithms in computer science.

Algorithms are like the backbone of computer science! They are step-by-step procedures or formulas used for problem-solving and computation. Without algorithms, our digital world would be a chaotic mess!

Can you explain the role of algorithms in everyday technology?

Absolutely! Algorithms are at play in so many aspects of our daily lives, from search engines like Google to social media feeds and even in navigation apps like Waze. They help these technologies give us the best results quickly.

How do algorithms impact the efficiency of software and applications?

Algorithms are like the secret sauce that makes software and applications run smoothly and efficiently. They determine how fast a program can process data and provide results, making a huge difference in user experience.

Are there different types of algorithms that serve different purposes?

Oh, yes! There are plenty of algorithm types like sorting algorithms, searching algorithms, hashing algorithms, and more! Each type is tailored to solve specific kinds of problems efficiently.

Why is it important to understand algorithms for anyone in the field of computer science?

Understanding algorithms is like having a superpower in the world of computer science! It not only sharpens your problem-solving skills but also gives you a deeper insight into how technology works behind the scenes.

How can I improve my understanding of algorithms?

Practice, practice, practice! Solving algorithmic problems regularly, participating in coding challenges, and diving into algorithm courses can help you level up your algorithm game in no time.

Any fun facts about algorithms that might surprise me?

Oh, here’s a fun one for you! Did you know that the word “algorithm” actually comes from the name of a Persian mathematician, Al-Khwarizmi, who pioneered the concept in the 9th century? Cool, right?

Can you recommend any resources for learning more about algorithms?

Certainly! Online platforms like Coursera, Udemy, and Khan Academy offer fantastic courses on algorithms for learners of all levels. You can also check out books like “Introduction to Algorithms” by Cormen et al. for an in-depth study.

Is it possible to create my own algorithms?

Absolutely! Put your thinking cap on and get creative! You can start by designing algorithms for simple tasks and gradually move on to more complex problems. The sky’s the limit!

Hope these FAQs shed some light on the fascinating world of algorithms! 🚀 Thanks for tuning in!

You Might Also Like

Binary decision diagrams: simplifying complex decision processes, optimizing data search in binary search trees, binary search tree: structure, operations, and applications, binary tree search: navigating trees for efficient data retrieval, searching in a binary search tree: algorithms and efficiency.

Avatar photo

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest Posts

79 Ultimate Guide to Hybrid Network Mobility Support Project in Named Data Networking

Ultimate Guide to Hybrid Network Mobility Support Project in Named Data Networking

68 Enhanced Security Network Coding System Project for Two-Way Relay Networks

Enhanced Security Network Coding System Project for Two-Way Relay Networks

88 Cutting-Edge Network Security Project: Distributed Event-Triggered Trust Management for Wireless Sensor Networks

Cutting-Edge Network Security Project: Distributed Event-Triggered Trust Management for Wireless Sensor Networks

72 Wireless Ad Hoc Network Routing Protocols Under Security Attack Project

Wireless Ad Hoc Network Routing Protocols Under Security Attack Project

codewithc 61 1 Cutting-Edge Collaborative Network Security Project for Multi-Tenant Data Centers in Cloud Computing

Cutting-Edge Collaborative Network Security Project for Multi-Tenant Data Centers in Cloud Computing

Privacy overview.

Sign in to your account

Username or Email Address

Remember Me

Help | Advanced Search

Computer Science > Computation and Language

Title: chatglm-math: improving math problem-solving in large language models with a self-critique pipeline.

Abstract: Large language models (LLMs) have shown excellent mastering of human language, but still struggle in real-world applications that require mathematical problem-solving. While many strategies and datasets to enhance LLMs' mathematics are developed, it remains a challenge to simultaneously maintain and improve both language and mathematical capabilities in deployed LLM this http URL this work, we tailor the Self-Critique pipeline, which addresses the challenge in the feedback learning stage of LLM alignment. We first train a general Math-Critique model from the LLM itself to provide feedback signals. Then, we sequentially employ rejective fine-tuning and direct preference optimization over the LLM's own generations for data collection. Based on ChatGLM3-32B, we conduct a series of experiments on both academic and our newly created challenging dataset, MathUserEval. Results show that our pipeline significantly enhances the LLM's mathematical problem-solving while still improving its language ability, outperforming LLMs that could be two times larger. Related techniques have been deployed to ChatGLM\footnote{\url{ this https URL }}, an online serving LLM. Related evaluation dataset and scripts are released at \url{ this https URL }.

Submission history

Access paper:.

  • HTML (experimental)
  • Other Formats

license icon

References & Citations

  • Google Scholar
  • Semantic Scholar

BibTeX formatted citation

BibSonomy logo

Bibliographic and Citation Tools

Code, data and media associated with this article, recommenders and search tools.

  • Institution

arXivLabs: experimental projects with community collaborators

arXivLabs is a framework that allows collaborators to develop and share new arXiv features directly on our website.

Both individuals and organizations that work with arXivLabs have embraced and accepted our values of openness, community, excellence, and user data privacy. arXiv is committed to these values and only works with partners that adhere to them.

Have an idea for a project that will add value for arXiv's community? Learn more about arXivLabs .

IMAGES

  1. Algorithms I Stanford Online

    algorithmic problem solving computer science

  2. Step Flow Chart Flowchart Diagram Algorithm Computer Science Png Image

    algorithmic problem solving computer science

  3. Unit2 algorithmic problem_solving

    algorithmic problem solving computer science

  4. PPT

    algorithmic problem solving computer science

  5. Examples of Algorithm| Problem Solving Chapter no.1

    algorithmic problem solving computer science

  6. Algorithmic problem solving

    algorithmic problem solving computer science

VIDEO

  1. Iterative Algorithms

  2. Harvard CS50 2023

  3. Level 2 Computing Lesson 6: Using Algorithms to Solve a Problem

  4. Data Structure Algorithm : Unlocking Secrets

  5. F.Y.B.Sc.(C.S.)|Sem-I |CS-111: Problem Solving using Computer and C Programming

  6. Detect Cycle In An Undirected Graph

COMMENTS

  1. Understanding Algorithms: The Key to Problem-Solving Mastery

    In the realm of computer science and beyond, everything revolves around problem-solving, and algorithms are our most reliable problem-solving tools. They provide a structured approach to problem-solving, breaking down complex problems into manageable steps and ensuring that every eventuality is accounted for.

  2. Algorithms

    Learn. We've partnered with Dartmouth college professors Tom Cormen and Devin Balkcom to teach introductory computer science algorithms, including searching, sorting, recursion, and graph theory. Learn with a combination of articles, visualizations, quizzes, and coding challenges.

  3. Algorithms

    Try parallel computing yourself. Learn to define algorithms, express them in flow chart and pseudocode, and assess their correctness and efficiency. See how algorithms can be used as shortcuts to solve problems that cannot be solved in a reasonable amount of time, and how this applies to undecidable problems and parallel and distributed computing.

  4. Algorithms Tutorial

    An algorithm is a step-by-step procedure for solving a problem or accomplishing a task. In the context of data structures and algorithms, it is a set of well-defined instructions for performing a specific computational task. Algorithms are fundamental to computer science and play very important role in designing efficient solutions for various problems.

  5. How to use algorithms to solve everyday problems

    My approach to making algorithms compelling was focusing on comparisons. I take algorithms and put them in a scene from everyday life, such as matching socks from a pile, putting books on a shelf, remembering things, driving from one point to another, or cutting an onion. These activities can be mapped to one or more fundamental algorithms ...

  6. What Is an Algorithm?

    An algorithm is a set of steps for accomplishing a task or solving a problem. Typically, algorithms are executed by computers, but we also rely on algorithms in our daily lives. ... In the context of computer science, an algorithm is a mathematical process for solving a problem using a finite number of steps. Algorithms are a key component of ...

  7. Sequencing, selection, and iteration

    AP®︎/College Computer Science Principles. ... An algorithm is a step by step process that describes how to solve a problem in a way that always gives a correct answer. When there are multiple algorithms for a particular problem (and there often are!), the best algorithm is typically the one that solves it the fastest. ...

  8. PDF Principles of Algorithmic Problem Solving

    Algorithmic problem solving is the art of formulating efficient methods that solve problems of a mathematical nature. From the many numerical algo-rithms developed by the ancient Babylonians to the founding of graph theory by Euler, algorithmic problem solving has been a popular intellectual pursuit during the last few thousand years.

  9. Best Algorithms Courses Online [2024]

    Learning to understand and apply algorithmic techniques for problem solving is an incredibly important skill for solving complex computing problems, and studying this field requires more specialized prerequisites than some programming-focused computer science courses. ... computer science, and how algorithms work via inputs and outputs ...

  10. Computer science

    An algorithm is a specific procedure for solving a well-defined computational problem. The development and analysis of algorithms is fundamental to all aspects of computer science: artificial intelligence, databases, graphics, networking, operating systems, security, and so on. Algorithm development is more than just programming.

  11. What is Algorithm

    Definition of Algorithm. The word Algorithm means " A set of finite rules or instructions to be followed in calculations or other problem-solving operations ". Or. " A procedure for solving a mathematical problem in a finite number of steps that frequently involves recursive operations".

  12. Problem-Solving Strategies

    A basic problem-solving process, in any discipline, starts with outlining the problem requirements and terminates with outlining a solution that, in some cases, is expressed by a sequence of steps (an algorithm) that solves the problem. In computer science, in many cases, the algorithm is coded into a programming language and is tested by the ...

  13. What is an Algorithm? Algorithm Definition for Computer Science Beginners

    An algorithm is a set of steps for solving a known problem. Most algorithms are implemented to run following the four steps below: Some steps of the algorithm may run repeatedly, but in the end, termination is what ends an algorithm. For example, the algorithm below sort numbers in descending order.

  14. 1: Algorithmic Problem Solving

    1.1: Activity 1 - Introduction to Algorithms and Problem Solving. In this learning activity section, the learner will be introduced to algorithms and how to write algorithms to solve tasks faced by learners or everyday problems. Examples of the algorithm are also provided with a specific application to everyday problems that the learner is ...

  15. How to Use Algorithms to Solve Problems?

    Let's take some examples of algorithms for computer science problems. Example 1. Swap two numbers with a third variable. Step 1: Start. Step 2: Take 2 numbers as input. Step 3: Declare another variable as "temp". Step 4: Store the first variable to "temp". Step 5: Store the second variable to the First variable.

  16. Learn Algorithmic Thinking Online

    It involves a systematic approach to problem-solving and analyzing tasks, where one identifies the necessary steps or actions required to achieve a specific goal or solve a particular problem. Algorithmic thinking is crucial in various fields such as computer science, programming, mathematics, and even everyday tasks.

  17. Practice Computer Science

    Take a guided, problem-solving based approach to learning Computer Science. ... Kruskal's Algorithm Strings Regular Expressions Algorithms. Algorithms Divide and Conquer ...

  18. Heuristics & approximate solutions

    All of these are combinatorial problems, where a computer would need to search an exponentially growing number of combinations to find the optimal answer. Combinatorial problems are quite common in the real world, so both companies and computer scientists alike care deeply about finding heuristics that will give the best approximate solutions.

  19. Mastering Algorithms: Practical Approach in Python

    Unlock the secrets of efficient problem-solving and algorithmic optimization with our "Mastering Algorithms" course. Whether you're a computer science student, a seasoned software engineer, or an aspiring coder, this course is designed to elevate your understanding of algorithm design, implementation, and analysis. Course Highlights: 1.

  20. Algorithmic Thinking in Computer Science

    Algorithmic Thinking has recently become a buzzword among programmers. It is a method for solving problems based on a clear definition of the steps: logically and repeatedly. The best idea would ...

  21. Fundamentals of Algorithmic Problem Solving

    An input to an algorithm specifies an instance of the problem the algorithm solves. It is very important to specify exactly the set of instances the algorithm needs to handle. (As an example, recall the variations in the set of instances for the three greatest common divisor algorithms discussed in the previous section.)

  22. Understanding Algorithms: The Foundation of Computer Science

    It not only sharpens your problem-solving skills but also gives you a deeper insight into how technology works behind the scenes. How can I improve my understanding of algorithms? Practice, practice, practice! Solving algorithmic problems regularly, participating in coding challenges, and diving into algorithm courses can help you level up your ...

  23. CIE IGCSE Computer Science

    The purpose of the algorithm below is to add ten user-entered numbers together and output the total. The processes are: initializing three variables (Count, Number, Total) inputting a user number. adding to two variables (Total, Count) repeating nine more times. outputting the final Total value. Count ← 1.

  24. [2404.02575] Language Models as Compilers: Simulating Pseudocode

    Algorithmic reasoning refers to the ability to understand the complex patterns behind the problem and decompose them into a sequence of reasoning steps towards the solution. Such nature of algorithmic reasoning makes it a challenge for large language models (LLMs), even though they have demonstrated promising performance in other reasoning tasks. Within this context, some recent studies use ...

  25. [2404.03441] Benchmarking ChatGPT on Algorithmic Reasoning

    Computer Science > Artificial Intelligence. arXiv:2404.03441 (cs) [Submitted on 4 Apr 2024] ... The benchmark requires the use of a specified classical algorithm to solve a given problem. We find that ChatGPT outperforms specialist GNN models, using Python to successfully solve these problems. This raises new points in the discussion about ...

  26. [2404.02893] ChatGLM-Math: Improving Math Problem-Solving in Large

    Large language models (LLMs) have shown excellent mastering of human language, but still struggle in real-world applications that require mathematical problem-solving. While many strategies and datasets to enhance LLMs' mathematics are developed, it remains a challenge to simultaneously maintain and improve both language and mathematical capabilities in deployed LLM systems.In this work, we ...